扫描仪中的nextLine方法

use*_*466 1 java

可能重复:
在nextInt之后使用nextLine时出现扫描程序问题

为什么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.");

    }
}
Run Code Online (Sandbox Code Playgroud)

Aus*_*tin 6

检查这个问题,

在nextXXX之后使用nextLine时扫描程序问题

看看接受的答案,

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