2016-09-26 211 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

相关问题