gpt4 book ai didi

Java 输入不匹配异常错误。我该如何解决这个问题?

转载 作者:行者123 更新时间:2023-12-02 11:25:50 25 4
gpt4 key购买 nike

仅当我输入 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);
}
}

最佳答案

扫描仪正在尝试读取 the nextInt methodint .

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

  • nextInt(基数):

Throws:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

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

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

如果你想输入任意数量的数字,只需调用next,获取字符串,并验证它是否只包含数字。在进一步处理之前,您需要将字符数字转换为数字类型。

关于Java 输入不匹配异常错误。我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com