gpt4 book ai didi

java - 当用户输入非 double 值时如何打印错误消息?

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:09 24 4
gpt4 key购买 nike

我正在尝试创建一个Java程序,从用户那里读取 double 值,打印这两个数字之间的差值,以便差值始终为正。如果输入数字以外的任何内容,我需要显示错误消息。请帮忙,谢谢!!

当我运行程序并输入第二个 double 值时,没有任何反应。我也尝试添加 try 和 catch 但出现错误,指出 num1 无法解析为变量:(

import java.util.Scanner;
public class Positive {

public static void main(String[] args) {

//Reads input
Scanner sc = new Scanner(System.in);

System.out.println ("Please enter a double vaule: ");

double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;

if (sc.hasNextDouble()) {
num1 = sc.nextDouble();

if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}

if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}

}else {
System.out.println("Wrong vaule entered");
}

}
}

最佳答案

你的想法是对的。您只需删除最后一个 if 后面的分号 (;) 并正确嵌套您的条件:

if (sc.hasNextDouble()) {
num1 = sc.nextDouble();

if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}

关于java - 当用户输入非 double 值时如何打印错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53134711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com