从扫描器输入Java接收浮点值
我需要一个方法来检查用户的输入是否是浮点,如果是字符串或int,则应该抛出一个异常 我在方法之外声明扫描仪:从扫描器输入Java接收浮点值,java,floating-point,java.util.scanner,Java,Floating Point,Java.util.scanner,我需要一个方法来检查用户的输入是否是浮点,如果是字符串或int,则应该抛出一个异常 我在方法之外声明扫描仪: Scanner sc = new Scanner(System.in); 方法定义为: private boolean CheckFloat(Scanner sc) throws MyException { if(!sc.hasNextFloat()){ throw new MyException("Wrong type"); } els
Scanner sc = new Scanner(System.in);
方法定义为:
private boolean CheckFloat(Scanner sc) throws MyException {
if(!sc.hasNextFloat()){
throw new MyException("Wrong type");
}
else {
float input = sc.nextFloat();
if(input%1==0) {
throw new MyException("Wrong type");
}
else return true;
}
}
问题是不管用户输入什么,都会抛出异常,所以我的问题是:我到底做错了什么
我知道在Java中,像1.2这样的输入被解释为double,但是如何从控制台获取浮点值呢?还是我误解了hasNextFloat()方法或整个扫描仪的工作
由于您正在使用
nextFloat()
必须确保输入浮点数,否则请使用next()
结果:
更新
您仍然需要处理InputMismatchException,只需在catch块中抛出您自己的异常即可
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// while (true) just for testing
while (true) {
try {
System.out.print("Enter a float: ");
System.out.println(CheckFloat(input));
} catch (MyException me) {
System.out.println(me.toString());
}
}
}
private static float CheckFloat(Scanner sc) throws MyException {
try {
float input = sc.nextFloat();
if (input % 1 == 0) {
throw new MyException("Wrong type");
} else {
return input;
}
} catch (InputMismatchException ime) {
sc.next(); // Flush the scanner
// Rethrow your own exception
throw new MyException("Wrong type");
}
}
private static class MyException extends Exception {
// You exception details
public MyException(String message) {
super(message);
}
}
结果:
您可能需要在开始使用之前致电sc.next()!sc.hasNextFloat()好的,对不起,我累了:p但对我来说,当我给出正确的浮点输入时,它仍然抛出异常。我更正了我的代码,我注意到它也只接受逗号符号,这就是为什么你的解决方案不能正确地为我工作。。。所以我想我现在应该换个地方。对不起,还是非常感谢你的帮助
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// while (true) just for testing
while (true) {
try {
System.out.print("Enter a float: ");
System.out.println(CheckFloat(input));
} catch (MyException me) {
System.out.println(me.toString());
}
}
}
private static float CheckFloat(Scanner sc) throws MyException {
try {
float input = sc.nextFloat();
if (input % 1 == 0) {
throw new MyException("Wrong type");
} else {
return input;
}
} catch (InputMismatchException ime) {
sc.next(); // Flush the scanner
// Rethrow your own exception
throw new MyException("Wrong type");
}
}
private static class MyException extends Exception {
// You exception details
public MyException(String message) {
super(message);
}
}