InputMismatchException

InputMismatchException

仅当我输入10个或更多3和7的数字时才会显示。它来自下面的此方法,我没有使用此方法进行了测试。这是代码

Scanner input = new Scanner(System.in);
    System.out.print("Enter a positive integer...");
    int num = input.nextInt();

    // Outputs
    System.out.println("Number of digits in number is " + numberDigits(num));
    System.out.println("Number begins with " + firstNum(num));
    System.out.println("Number ends with " + lastNum(num));
    System.out.println("Does number begin with 7? " + beginWith(num, 7));
    System.out.println("Does number begin with 3? " + beginWith(num, 3));
    System.out.println("Does number contain a 7? " + contains(num, 7));
    System.out.println("Does number contain a 3? " + contains(num, 3));
    System.out.println("Is the number divisible by 13? " + divTest(num, 13));
    System.out.println("Is the number divisible by 77? " + divTest(num, 77));
    System.out.println("How many times does 7 appear in the number? " + digitAppearances(num, 7));
    System.out.println("How many times does 3 appear in the number? " + digitAppearances(num, 3));

public static int digitAppearances(int num, int x) {

    // Check if num is 0
  if (num <= 0 ) {
    return 0;
  }

// Count number of times x appears
else if (num % 10 == x) {
    return 1 + digitAppearances(num / 10, x);
}
else {
    return digitAppearances(num / 10, x);
}
}

最佳答案

Scanner尝试使用the int method读取nextInt


  调用此格式为nextInt()的方法的行为与调用nextInt(radix)的行为完全相同,其中radix是此扫描程序的默认基数。



nextInt(基数):



  抛出:
  
  InputMismatchException-如果下一个标记与Integer正则表达式不匹配或超出范围


如果输入的值大于Integer.MAX_VALUE(约21亿,10位数字),则将得到InputMismatchException

如果要输入最多19位数字,请使用nextLong

如果要输入任意位数,只需调用next,获取字符串,并验证它仅包含数字即可。您需要先将字符数字转换为数字类型,然后再进行进一步处理。

关于java - Java InputMismatchException错误。我将如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49640214/

10-11 14:29