2011-04-20 148 views
3

我想要做的是獲得用戶輸入,將其轉換爲整數,創建一個變量並將整數存儲到該新變量的循環。如果用戶沒有輸入單詞「結束」,它將繼續這樣做,直到用戶這樣做。我遇到的問題是創建變量。我只想讓他們有a,b,c,d,e等等。我可以做的其他程序只是需要指出正確的方向。在循環中初始化變量

+4

你可以發佈你目前的(非工作)代碼,並解釋你到底有什麼問題嗎? – Oded 2011-04-20 19:04:07

+1

關於downvoters/closers的說明 - 家庭作業問題是有效的,OP已經在一個這樣的問題中清楚地表明瞭這一點。 – Oded 2011-04-20 19:05:55

+1

@Oded這是標記作業,但它仍然像「寫給我的代碼」:/ – 2011-04-20 19:06:48

回答

2

如果你不知道你會得到多少值,你真的需要將它們存儲在Collection,如List

一旦它們全部輸入,你將如何處理這些值?

1

如果你是在一個循環中,賠率是你不需要在循環來實現一個新的變量,因此不是像

int input1; 
int input2; 
int input3; 
int input4; 
int input5; 
for (int index = 0; index < 5; index++) { 
    if (index == 0) { 
    input1 = getInput(); 
    } 
    if (index == 1) { 
    input2 = getInput(); 
    } 
    if (index == 2) { 
    input3 = getInput(); 
    } 
    if (index == 3) { 
    input4 = getInput(); 
    } 
    if (index == 4) { 
    input5 = getInput(); 
    } 
} 

的解決方案,也許可以與類似的解決方案活

int input; 

for (int index = 0; index < 5; index++) { 
    input = getInput(); 
    ... handle input before going through next loop iteration ... 
} 

請注意,使用switch語句的解決方案只是優化不需要的「太多if」解決方案。

2

我會用一個陣列,這和它聽起來像你需要兩個變量:

String sInput; 

int iInput[]; 

然後在你的循環,你可以測試一下,看看是否sInput是數字,而不是「結束」之後就可以它分析你的陣列:

iInput[index] = Integer.parseInt(sInput); 

以後你就可以在陣列iInput[0]iInput[1]在訪問每個元素...

要知道你必須d efine數組的大小,當你用Java來做時,你不能改變它或者使它變大。

我希望這會讓你走。

+0

編輯格式。 – phooji 2011-04-20 19:57:17