Java 在传递给方法的扫描程序对象上使用分隔符

Java 在传递给方法的扫描程序对象上使用分隔符,java,Java,此问题链接到此网站上的另一个问题: 相关实践站点创建类并调用您使用以下调用编写的方法: inputBirthdaynew Scanner8\n可能\n1981\n 我很想知道为什么它也不起作用。我的方法代码如下: public static void inputBirthday(Scanner scan) { System.out.print("On what day of the month were you born? "); int monInt = scan.nextIn

此问题链接到此网站上的另一个问题:

相关实践站点创建类并调用您使用以下调用编写的方法: inputBirthdaynew Scanner8\n可能\n1981\n

我很想知道为什么它也不起作用。我的方法代码如下:

public static void inputBirthday(Scanner scan) {
    System.out.print("On what day of the month were you born? ");
    int monInt = scan.nextInt();
    System.out.print("What is the name of the month in which you were 
    born? ");
    String monStr = scan.nextLine();
    System.out.print("During what year were you born? ");
    int year = scan.nextInt();
    scan.close();
    System.out.println("You were born on " + monStr + ", " + monInt + year 
    + ". You're mighty old!");
}
我不断地发现这个错误:

NoTouchElementException:输入行3附近的“May”不能解释为int类型

在我的代码的这一行之后:

int year = s.nextInt();

有什么想法吗?谢谢

当您输入您出生月份的日期并按enter键时,即

System.out.print("On what day of the month were you born? ");
    int monInt = scan.nextInt();
您希望他们输入一个数字。如果他们输入13并按enter键,计算机将看到您输入了13\n,就像您也按enter键一样。您对nextInt的呼叫将读取13,但保留\n。nextLine的工作方式是一直读取,直到下一次出现\n,因为\n用于结束一行。问题是你现在正在打电话 你是哪一年出生的; int year=scan.nextInt; 接下来,您仍然希望输入他们出生月份的字符串表示形式。因此,当您输入字符串时,对nextInt的调用不能被解析为整数,因为它不是整数-它是字符串! 您有两个选项可以解决此问题-您可以在第一次调用nextInt后直接调用scan.nextLine以从输入缓冲区中删除\n,也可以使用scan.next而不是scan.nextLine来存储月份的字符串表示形式。next通常会一直读取到下一个空格,因此输入缓冲区中仍然存在的\n不会引起任何问题。代码的功能版本如下所示:

public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("On what day of the month were you born? ");
        int monInt = input.nextInt();
        System.out.print("What is the name of the month in which you were born? ");
        String monStr = input.next();
        System.out.print("During what year were you born? ");
        int year = input.nextInt();
        input.close();
        System.out.println("You were born on " + monStr + ", " + monInt + year
                + ". You're mighty old!");
    }
这个程序的一个输出示例是

On what day of the month were you born? 13
What is the name of the month in which you were born? October
During what year were you born? 1943
You were born on October, 131943. You're mighty old!
请注意,您仍然必须更改文本格式,以使其完全按照您可能希望的方式输出,但您以前遇到的问题已得到解决。

Parsing 8\n可能\n1981\n


所以问题是,下一行读取的是第一行的末尾,而不是Mays行。

可能重复使用下一行而不是下一行来读取月份。请将错误格式化为代码。这看起来一团糟。
    int monInt = input.nextInt(); // Reads 8
    System.out.print("What is the name of the month in which you were born? ");
    String monStr = input.nextLine(); // Reads to end of line, aka '\n'
    System.out.print("During what year were you born? ");
    int year = input.nextInt(); // reads next token as int, which is "May"