gpt4 book ai didi

java - 带循环开关

转载 作者:行者123 更新时间:2023-12-02 00:03:13 25 4
gpt4 key购买 nike

我正在尝试使用 switch 语句创建一个循环。如果用户未在 1 到 4 之间输入,则会重复出现“您输入错误选项”的消息。我正在制作 Lynda 视频。我不知道该把循环放在哪里。我目前找不到让它循环的方法。是在switch中还是在getInput方法中。是否有可能做到这一点?如果有人知道的话,先谢谢了。我正在使用 eclipse,java 7。

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



double result = 0;
do {
String op = getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");
int opInt = Integer.parseInt(op);
switch (opInt)
{
case 1:
result = addValues(s1, s2);
break;
}
} while(opInt<1 || opInt >4);

编辑错误消息...

该行有多个标记- opInt 无法解析为 变量

  • opInt 无法解析为变量

    //在其他数学运算符中我有一个名为 addValues 的方法

    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 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();
    }
    }

    编辑我对 Tal 和 Quoi 给我的解决方案有疑问。使用 Quoi 时,我收到 opInt 无法解析为变量的错误,因为使用 Tal 时什么也没有发生。

所以我做了以下...

String s1 = getInput("Enter a numeric value: ");
String s2 = getInput("Enter a numeric value: ");
String op = getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");

//convert opInt into integer
int opInt = Integer.parseInt(op);

if (opInt <1 || opInt >4) // used a if statement
{
getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");
}

double result = 0;
{
switch (opInt)
{
...........
...........
}
}

使用 if 语句,该方法会回调 switch 语句,但在选择正确的选项后,会显示“您输入了错误的选项”和“答案是 0.0”的打印行,因此不会进行任何计算。我不确定这是一个简单的解决方案还是什么?

编辑我现在尝试在开关外做一个 while 循环。发生的情况是,当我选择 1 或 4 之外的选项时,无论我是否输入有效选项,我都会再次收到“输入 1=加、2=减、3=乘、4=除”消息。

do 
{
getInput("Enter 1=Add, 2=Subtract, 3=Multiply, 4=Divide");
} while (opInt <1 || opInt >4);

double result = 0;
{
switch (opInt)
{
case 1:
result = addValues(s1, s2);
break;
...........
...........
}
}

最佳答案

switch-case 放入循环内。

do{
String op = getInput("Enter 1=Add, 2=Subtract, 3=Multiply,
4=Divide");
int opInt = Integer.parseInt(op);

switch(opInt){
case 1: ... break;
case 2: ... break;
case 3: ... break;
case 4: ... break;
}
}while(opInt<1 || opInt >4);

关于java - 带循环开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14417660/

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