英文:
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("");
}
else if (number % 2 == 0) {
System.out.println("even");
}
else {
System.out.println("odd");
}
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论