输入不匹配错误,在扫描数字时发生错误。

huangapple go评论85阅读模式
英文:

InputMismatchError while scanning number

问题

尝试使用以下代码读取数字时会生成 InputMismatchError

Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // 此处出错

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}

我不明白错误出在哪里。Eclipse 编译程序没有错误。

以下是从控制台使用的输入:

1234.5

英文:

While trying to read a number using below code InputMismatchError is generated:

Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // Error here

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}

I don't understand where a mistake. Eclipse compiled program without errors.

Following is the input from console used

1234.5

答案1

得分: 0

当输入可能包含一些非整数值时,您应该检查下一个值是否为“long”。如果不是,请忽略它:

while (sc.hasNext()) {
// 检查下一个是否为long类型
if (sc.hasNextLong()) {
long number = sc.nextLong();

    if (number == 0) {
        System.out.println("");
    }
    else if (number % 2 == 0) {
        System.out.println("even");
    }
    else {
        System.out.println("odd");
    }
}
else {
    // 不是long类型,消耗掉该行的剩余部分。
    // 根据需求,您可能需要更改为 sc.next()。
    sc.nextLine();
}

}


<details>
<summary>英文:</summary>

If the input might have some non-integers with the values, you should check if the next value is a `long`. If not, ignore it:

while (sc.hasNext()) {
// Check if next is a long
if (sc.hasNextLong()) {
long number = sc.nextLong();

	if (number == 0) {
		System.out.println(&quot;&quot;);
	}
	else if (number % 2 == 0) {
		System.out.println(&quot;even&quot;);
	}
	else {
		System.out.println(&quot;odd&quot;);
	}
}
else {
	// Not a long, consume rest of line.
	// You might need to change this to sc.next() depending on requirements
	sc.nextLine();
}

}


</details>



# 答案2
**得分**: 0

你可以这样做:

```java
Scanner scan = new Scanner(System.in);
long val = scan.nextLong();
System.out.printf(String.valueOf(val));

当你期望输入长整型时,应该从命令行传递非十进制数值。

英文:

You could do this way

Scanner scan = new Scanner(System.in);
long val = scan.nextLong();
System.out.printf(String.valueOf(val));

while you are expecting long you should pass non-decimal numeric value from command line.

huangapple
  • 本文由 发表于 2020年5月29日 22:04:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/62087790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定