扫描仪中的nextLine方法

时间:2012-10-12 21:50:33

标签: java

  

可能重复:
  Scanner issue when using nextLine after nextInt

为什么丈夫下的空sc.nextLine();如此必要?它并不等于任何东西,而且妻子肯定没有那条线......但如果没有它,程序将无法运行。我的书将其评为Skip over尾随newLine角色。但是我看不出有什么可以跳过的!

public class FileTest {
    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.print("For your blended family, \n enter the wife's name");
    String wife = sc.nextLine();
    System.out.print("Enter the number of her children:");
    int herkids = sc.nextInt();

    System.out.print("Enter the husband's name:");
    //sc.nextLine();  // Why is this line so necessary? 
    String husband = sc.nextLine();
    System.out.print("Enter the number of his children:");
    int hisKids = sc.nextInt();

    System.out.println(wife + " and " + husband + " have " + (herkids + hisKids) + " children.");

    }
}

1 个答案:

答案 0 :(得分:6)

检查这个问题,

Scanner issue when using nextLine after nextXXX

看看接受的答案,

“问题在于input.nextInt()命令它只读取int值。所以当你继续读取input.nextLine()时,你会收到”\ n“Enter键。所以要跳过这个你必须添加input.nextLine()。希望现在应该清楚。“