获取InputMismatchException

时间:2018-11-28 21:50:22

标签: java

我在这里有这段代码:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a positive integer: ");
    int i = input.nextInt();
    recursiveMethod(i);
    System.out.println();
    System.out.print("Enter a string: ");
    String s = input.next();
    System.out.print("Enter a positive integer: ");
    int j = input.nextInt();
    recursiveMethod(s, j);
}

public static void recursiveMethod(int i) {
    if (i != 0) {
        System.out.print("*");
        i--;
        recursiveMethod(i);
    }
}

public static void recursiveMethod(String s, int j) {
        if (j != 0) {
            System.out.println(s);
            j--;
            recursiveMethod(s, j);
        }
}

运行此命令时,出现以下错误:

Enter a positive integer: 8
********
Enter a string: Run faster.
Enter a positive integer: 
Exception in thread "main" 
java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.company.Main.main(Main.java:16)

Process finished with exit code 1

我不确定是怎么回事,尽管当我将字符串作为带有空格的短语输入时,似乎会使程序崩溃。

0 个答案:

没有答案