2017-10-04 173 views
-2

在這個程序中,我的意思是說:它應該只能從用戶那裏通過掃描儀獲得正數,如果它們是正數 - 它需要將它們添加到「列表」數組列表中。 由於某些原因,它不會在用戶添加第一個數字時添加第一個數字,而只會添加第二個數字(並且它在每個while循環中都像這樣運行)。ArrayList的掃描儀

有人可以幫忙嗎? 謝謝! :-)

import java.util.ArrayList; 
import java.util.Scanner; 
import java.util.ArrayList; 
public class Second_EX_Advanced_2 { 
    public static void main(String[] args) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     System.out.println("Please enter a positive number ... "); 
     Scanner INPUT = new Scanner(System.in); 
     while (INPUT.nextInt() > 0) { 
      list.add(INPUT.nextInt()); 
      System.out.println(list); 
     } 
     INPUT.close(); 
    } 
} 

*

+2

你是消費在'while'條件的第一整數值。 – Mena

+0

'while((value = INPUT.nextInt())> 0)'其中'value'的類型是int,然後是'list.add(value);' – XtremeBaumer

+0

使用nextLine()將清除緩衝區,您在錯誤之後讀取的下一個輸入將是您輸入的壞行之後的新輸入。 – VedX

回答

1

你實際上走的是輸入兩次

while (INPUT.nextInt() > 0) { //first time here 
     list.add(INPUT.nextInt()); //second time here 
     System.out.println(list); 
    } 

變化

int n; 
while ((n=INPUT.nextInt()) > 0) { //first time here 
     list.add(n); //second time here 
     System.out.println(list); 
    } 

現在應該很好地工作;

0

錯誤是在,而你的循環:

while (INPUT.nextInt() > 0) { 
      list.add(INPUT.nextInt()); 
      System.out.println(list); 
     } 

要掃描的第一個整數並加入第二個,如上所述。

在這裏,你去與工作代碼:

import java.util.ArrayList; 
import java.util.Scanner; 
import java.util.ArrayList; 
public class Second_EX_Advanced_2 { 
    public static void main(String[] args) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     System.out.println("Please enter a positive number ... "); 
     Scanner INPUT = new Scanner(System.in); 
     int num; 
     while ((num = INPUT.nextInt()) > 0) { 
      list.add(num); 
      System.out.println(list); 
     } 
     INPUT.close(); 
    } 
} 
+0

謝謝所有:)它幫助分配 – Ofer

+0

您可以通過單擊答案旁邊的箭頭接受此答案。這對社區有幫助。 :) –