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

时间:2017-05-19 19:17:49

标签: java

此问题与本网站上的另一个问题有关:

Beginner in Java - Using Parameters and Scanner

有问题的练习网站创建了这个类,并使用以下调用调用您编写的方法: inputBirthday(new Scanner(“8 \ nMay \ 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!");
}

我一直收到这个错误:

“NoSuchElementException:接近输入行3token'May'不能解释为int类型,”

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

int year = s.nextInt();

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

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

${message}

您希望他们输入一个号码。如果他们输入13并按Enter键,计算机将看到您已输入System.out.print("On what day of the month were you born? "); int monInt = scan.nextInt(); ,因为您还按了Enter键。您对nextInt()的调用将会读取13\n,但请离开13。 nextLine()的工作方式是,它会一直读到\n的下一次出现,因为\n用于结束一行。这个问题是现在你正在打电话 \n 接下来,你仍然希望输入他们出生月份的字符串表示。因此,当你输入String时,你对nextInt()的调用不能被解析为整数,因为它不是一个整数 - 它是一个字符串! 你有两种方法可以解决这个问题 - 你可以在第一次调用nextInt()之后直接调用scan.nextLine(),以便从输入缓冲区中剥离System.out.print("During what year were you born? "); int year = scan.nextInt();,或者你可以使用scan.next()而不是scan.nextLine()来存储月份的String表示形式。 next()将(通常)读取直到下一个空格,因此输入缓冲区中仍然存在的\n不会导致任何问题。代码的功能版本如下 -

\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!");
    }

请注意,您仍然需要更改文本格式以使其完全按照您的需要进行输出,但您之前遇到的问题已得到解决。

答案 1 :(得分:0)

使用

解析"8\nMay\n1981\n "
    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"

所以问题是nextLine()正在读取第一行的末尾,而不是Mays行。