2016-09-26 131 views
0

我想寫一個代碼,要求用戶輸入他們的名字,將它存儲在列表中,然後要求他們輸入他們的年齡,將它存儲在另一個列表中。然後詢問用戶是否想再次嘗試[是/否]。 當測試代碼時,我輸入「Y」,並期望循環要求我輸入另一個名稱。相反,它跳過名稱輸入並跳轉到年齡輸入。我無法弄清楚爲什麼。 代碼如下爲什麼此循環的第二次迭代會跳過第一次掃描?

import java.util.ArrayList; 
import java.util.Scanner; 

public class PatternDemoPlus { 
    public static void main(String[] args){ 
     Scanner scan = new Scanner(System.in); 
     ArrayList<String> names = new ArrayList<String>(); 
     ArrayList<Integer> ages = new ArrayList<Integer>(); 
     String repeat = "Y"; 
     while(repeat.equalsIgnoreCase("Y")){ 
      System.out.print("Enter the name: "); 
      names.add(scan.nextLine()); 
      System.out.print("Enter the age: "); 
      ages.add(scan.nextInt()); 

      System.out.print("Would you like to try again? [Y/N]"); 
      repeat = scan.next(); 
      //Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N] 
      System.out.println(repeat); 

      //Why is it that after the first iteration, it skips names.add and jumps right to ages.add? 
     } 
    } 
} 

我希望得到您的幫助。謝謝。

+0

提示:您是否檢查過在'repeat = scan.next()'這一行收到的內容?注意輸入「123 XYZ」作爲年齡。 –

回答

0

使用next()將只返回空格前的內容。 nextLine()在返回當前行後自動向下移動掃描器。

嘗試更改您的代碼,如下所示。

public class PatternDemoPlus { 
    public static void main(String[] args){ 
     Scanner scan = new Scanner(System.in); 
     ArrayList<String> names = new ArrayList<String>(); 
     ArrayList<Integer> ages = new ArrayList<Integer>(); 
     String repeat = "Y"; 
     while(repeat.equalsIgnoreCase("Y")){ 
      System.out.print("Enter the name: "); 
      String s =scan.nextLine(); 
      names.add(s); 
      System.out.print("Enter the age: "); 
      ages.add(scan.nextInt()); 
      scan.nextLine(); 
      System.out.print("Would you like to try again? [Y/N]"); 
      repeat = scan.nextLine(); 

      System.out.println(repeat); 


     } 
    } 
} 
+1

我希望你已經嘗試輸入「比爾默裏」作爲名稱之前,你給這個答案:) –

+0

對不起阿德里安錯誤我已經把其他代碼...現在更新它 –

+0

我在我的代碼中的一個評論中提到它, //注意,如果我使用「repeat = scan.nextLine();相反,代碼不允許我輸入任何東西,它會卡住在」你想再試一次嗎? [是/否] – dou2abou

相關問題