gpt4 book ai didi

Java 验证基本计算器程序中的输入

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:54 25 4
gpt4 key购买 nike

我正在寻找如何使我的程序正确运行的答案。我希望我的程序能够识别 double 以外的东西——例如,如果我放入 idk ,它会说,这不是一个数字而不是崩溃。

我的代码:

import java.util.*;

public class CalculatorMain {
public static void main(String[] args) {

FunctionMain action = new FunctionMain();

Scanner input = new Scanner(System.in);

double answer = 0;
double inputNu1, inputNu2;
char operator;
boolean end = false;

while (! end ) {
System.out.print(">>>");

inputNu1 = input.nextDouble();
operator = input.next().charAt(0);
inputNu2 = input.nextDouble();

switch (operator)
{
case '-': answer = action.Subtract(inputNu1, inputNu2);
break;
case '*': answer = action.Multiply(inputNu1, inputNu2);
break;
case '+': answer = action.Add(inputNu1, inputNu2);
break;
case '/': answer = action.Divide(inputNu1, inputNu2);
break;
}

System.out.println(answer);
}
input.close();

}

}



public class FunctionMain {

double Subtract (double Nu1 , double Nu2)
{
return Nu1 + Nu2;

}
double Multiply (double Nu1 , double Nu2)
{
return Nu1 * Nu2;
}
double Add (double Nu1 , double Nu2)

{
return Nu1 + Nu2;
}
double Divide (double Nu1 , double Nu2)

{
return Nu1 / Nu2;
}

}

最佳答案

当您尝试将 String 转换为 Double 时,您会遇到异常,因此您必须按如下方式进行管理:

double n = 0.0;
try {
n = input.nextDouble();
} catch (Exception e) {
// there was an error, and here we can do whatever
System.out.println( "It was not a number!" );
}

了解有关异常(exception)的更多信息:http://docs.oracle.com/javase/tutorial/essential/exceptions/

关于Java 验证基本计算器程序中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470914/

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