运行程序时,出现以下错误:
输入一个数字: 5 你原来的号码是5.0 错误输入的不是数字。
我尝试了所有我能想到的方法,但我被难住了。以下是代码片段,
import java.util.Scanner;
public class NegativeNumberConversion {
public static void main(String[] args) {
// Convert negative numbers to positive and display back to user
// Create a console object for Scanner class
Scanner input = new Scanner (System.in);
// Declare variable
double numberOne = 0;
// Prompt user to enter number
System.out.println("Enter a number: ");
// Read in the number
numberOne = input.nextDouble();
// If the number is positive - display it
if (numberOne > 0){
// Display it - Explain that it is the original number
System.out.println("Your original number is " + numberOne);
}else {
// Report the error
System.out.println("***ERROR*** The input is not a number.");
// Terminate the error
System.exit(1);
}
// If the number negative - convert it to positive -
if(numberOne < 0){
// Display it - Explain that it was converted
System.out.println("Your number was converted to " + (-1*numberOne) + " because it was negative.");
}else{
// Report the error
System.out.println("***ERROR*** The input is not a number.");
// Terminate the error
System.exit(1);
}
// Close input
input.close();
}
}
最佳答案
问题在于 if 语句的设置方式
要解决此问题,请将第二种情况包含在 else if 中。
if (numberOne > 0) {
System.out.println("Your original number is " + numberOne);
}
else if (numberOne < 0) {
System.out.println("Your number was converted to " + (-1 * numberOne) + " because it was negative.");
}
else {
// Report the error
System.out.println("***ERROR*** The input is not a number.");
// Terminate the error
System.exit(1);
}
编辑:帮助您理解为什么它不起作用(而不是仅仅显示解决方案)。当有人输入一个输入时,无论它是正数还是负数,两个 if 语句都会进行比较,并且由于数字不能同时存在,因此始终会运行 else 语句之一。
关于java - 我的 'else' 语句有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32600202/