运行程序时,我收到以下错误:
输入数字: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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是你的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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:帮助您了解为什么它不起作用(而不仅仅是显示解决方案).当有人输入输入时,无论是正面还是负面,都会比较if语句和由于数字不能同时进行,因此其中一个else语句将始终运行.
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |