2015-01-08 33 views
-5

我想驗證輸入值只傳遞可被10整除的整數。下面的代碼失敗。如何只輸入整數,這個整數只會以零結尾?

public static void main(String args[]) { 
    Scanner scan =new Scanner(System.in); 
    ArrayList<Integer> liste = new ArrayList<Integer>(); // I have filled my array with integers 
    int x=scan.nextInt(); 
int y=x%10; 
do{ 
if(y==0){ 
liste.add(x);} 
else if(y!=0){ 
System.out.println("It is not valid"); continue; 
} 
else 
{System.out.println("Enter only integer"); continue; 
} 

}while(scan.hasNextInt()); } 

     System.out.println(liste); 
     System.out.println("Your largest value of your arraylist is: "+max(liste)); 
+0

'輸入代碼herepublic靜態無效的主要(字符串ARGS []){'是無效的方法簽名;) –

+3

你爲什麼不保存'scan.nextInt()'在變量中的結果而不是調用它兩次? –

回答

1

您打給scan.nextInt()兩次。每次你調用它時,它都會從輸入中讀取另一個int。因此,如果你的輸入是像

10 
5 
13 

那麼10會通過scan.nextInt()%10==0檢查,然後5將被添加到列表中。將scan.nextInt()的結果存儲在變量中,因此值不會更改。取而代之的

if(scan.nextInt()%10==0){ 
liste.add(scan.nextInt());} 

int num = scan.nextInt(); 
if(num%10 == 0){ 
    liste.add(num); 
} 
+0

我該如何解決這個問題 –

+0

是的,你是對的,它傳遞我的第一個價值 –

+0

用編碼編輯答案。 – Sizik

相關問題