java inputmismatch_java – 为什么我得到InputMismatchException?

在这里你可以看到Scanner的本质:

double nextDouble()

Returns the next token as a double. If the next token is not a float or

is out of range, InputMismatchException is thrown.

试着抓住异常

try {

// ...

} catch (InputMismatchException e) {

System.out.print(e.getMessage()); //try to find out specific reason.

}

UPDATE

情况1

我尝试了你的代码,它没有任何问题.您收到错误是因为您必须输入字符串值.当我输入一个数值时,它运行没有任何错误.但是一旦我输入了String,它就会抛出你在问题中提到的相同的异常.

案例2

您输入的内容超出了我上面提到的范围.

我真的很想知道你可以尝试进入什么.在我的系统中,它运行完美而无需更改单行代码.只需按原样复制并尝试编译并运行它.

import java.util.*;

public class Test {

public static void main(String... args) {

new Test().askForMarks(5);

}

public void askForMarks(int student) {

double marks[] = new double[student];

int index = 0;

Scanner reader = new Scanner(System.in);

while (index < student) {

System.out.print("Please enter a mark (0..30): ");

marks[index] = (double) checkValueWithin(0, 30);

index++;

}

}

public double checkValueWithin(int min, int max) {

double num;

Scanner reader = new Scanner(System.in);

num = reader.nextDouble();

while (num < min || num > max) {

System.out.print("Invalid. Re-enter number: ");

num = reader.nextDouble();

}

return num;

}

}

如你所说,你试图输入1.0,2.8等.请尝试使用此代码.

注意:请在单独的行中逐个输入数字.我的意思是,输入2.7,按回车键然后输入第二个号码(例如6.7).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值