Java双重错误
遵守这一准则Java双重错误,java,double,Java,Double,遵守这一准则 public static void main(String[] args) { Scanner wg= new Scanner(System.in); System.out.print("Enter your weight on the Earth "); double weight = wg.nextDouble(); double c; c=17*weight/100; System.out.println("Your we
public static void main(String[] args) {
Scanner wg= new Scanner(System.in);
System.out.print("Enter your weight on the Earth ");
double weight = wg.nextDouble();
double c;
c=17*weight/100;
System.out.println("Your weight on the Moon is: " + c);
wg.close();
}
问题是,当我输入双值时,它显示:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
您肯定使用了无效的双精度格式。例如,用法为“,”而不是“.” 每当用户键入与请求的值不同的值时,
扫描仪就会抛出。例如,在代码中调用Scanner\nextInt
时键入“hello”
这里发生的事情是,您调用了wg.nextDouble()
,但是用户键入了一些扫描程序无法识别为双重身份的内容。您应该在wg.nextDouble()
周围环绕一个try-catch块,以便知道用户何时键入非法值。将反输入作为字符串,并尝试解析为数字
public static void main(String[] args) {
Scanner wg= new Scanner(System.in);
System.out.print("Enter your weight on the Earth ");
String input = wg.next();
try{
double weight = Double.valueOf(input);
double c;
c= weight * 0.17;
System.out.println("Your weight on the Moon is: " + c);
wg.close();
}catch(Exception e){
System.out.println("Please insert a valid number! Ex: 10.6 ");
}
}
你们提供什么双重价值?
public static void main(String[] args) {
Scanner wg= new Scanner(System.in);
System.out.print("Enter your weight on the Earth ");
String input = wg.next();
try{
double weight = Double.valueOf(input);
double c;
c= weight * 0.17;
System.out.println("Your weight on the Moon is: " + c);
wg.close();
}catch(Exception e){
System.out.println("Please insert a valid number! Ex: 10.6 ");
}
}