gpt4 book ai didi

java - 我需要这个计算器来重定向用户输入,以防他输入错误

转载 作者:行者123 更新时间:2023-11-29 03:08:02 26 4
gpt4 key购买 nike

在第三个输入中,它要求输入一个数字来进行特定的操作。但是当输入例如“5”时,它不会自动将其发送到默认部分以显示消息“该值不存在”。除此之外,我还需要它再次显示输入提示并要求输入从 1 到 4 的数字。谢谢

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class Specialized {

public static void main(String[] args) {
String s1 = getInput("Enter a number: ");
String s2 = getInput("Enter a number: ");
String op = getInput("Enter: 1 = Add, 2 = Subtract, 3 = Multiply, 4 = Divide ");

int opInt = Integer.parseInt(op);
double result= 0;

switch (opInt) {
case 1:
result = addValues(s1,s2);
break;
case 2:
result = subtractValues(s1,s2);
break;
case 3:
result = multiplyValues(s1,s2);
break;
case 4:
result = divideValue(s1,s2);
break;
default:
System.out.println("the value doesn't exist.");
break;
}
System.out.println(result);
}

private static String getInput(String prompt) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();

try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}

private static double addValues(String s1, String s2)
throws NumberFormatException {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 + d2;
return result;
}

private static double subtractValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 - d2;
return result;
}

private static double multiplyValues(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 * d2;
return result;
}

private static double divideValue(String s1, String s2) {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
double result = d1 / d2;
return result;
}

}

最佳答案

通常,您用 while 循环包围“从用户那里获取输入”,直到获得所需的输入。像这样。

public static void main(String[] args) {
String s1 = getInput("Enter a number: ");
String s2 = getInput("Enter a number: ");

//notice I declare this outside now so I can compute for new value inside loop
int opInt = 0;
double result = 0;

//you can change the condition later if you add more options
while(opInt < 1 || opInt > 4) {
String op = getInput("Enter: 1 = Add, 2 = Subtract, 3 = Multiply, 4 = Divide ");
//recalculate the choice
opInt = Integer.parseInt(op);

switch (opInt) {
case 1:
result = addValues(s1, s2);
break;
case 2:
result = subtractValues(s1, s2);
break;
case 3:
result = multiplyValues(s1, s2);
break;
case 4:
result = divideValue(s1, s2);
break;
default:
System.out.println("the value doesn't exist.");
break;
}
}
System.out.println(result);
}

关于java - 我需要这个计算器来重定向用户输入,以防他输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054303/

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