-4

这个想法是,例如,如果他们选择 * if 会说错误的运算符,请再试一次,但目前如果我选择了错误的运算符,并且如果我选择了正确的运算符,程序需要结束,我似乎无法想办法

我的代码如下

 import java.util.Scanner;


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

    int tal1, tal2;
    int sum = 0;
    int sub=0;
    String operator;


    Scanner input = new Scanner (System.in);
    Scanner input2 = new Scanner (System.in);

    System.out.println("write in first digit");
    tal1 = input.nextInt();


    System.out.println("Write in 2nd digit ");
    tal2 = input.nextInt();

    System.out.println("Enter + to add and - subtract ");
    operator = input2.nextLine();


    while (operator.equals("-") || operator.equals("+")|| operator.equals("*")  || operator.equals(("/")) ){

    if (operator.equals("+")){
        sum = tal1+tal2;
        System.out.println("the sum is " + sum);
    }

    else if (operator.equals("-")){
        sub = tal1-tal2;
        System.out.println("the subtracted value  is " + sub);

    }
    if (operator.equals("*") || operator.equals("/")){ 
    System.out.println("You have put in the wrong operator, your options are + or -");
}

}

} }

4

4 回答 4

2

你的问题在这里:

operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*")  || operator.equals(("/")) )

假设operator+。的值在循环operator内不会改变,所以总是会改变,并且你有一个无限循环。whileoperator+

于 2013-11-02T21:53:44.910 回答
0

您的运营商将永远与众不同。因此,您的循环永远不会结束。您应该使用if而不是while

于 2013-11-02T21:53:07.013 回答
0

不要使用while循环,而是使用在从输入读取之前开始的do循环,并且仅在is not oroperator时才循环返回。理想情况下,循环结束时应该在您尝试计算之前出现。operator+-whiledo

于 2013-11-02T21:53:40.083 回答
0

好吧,当然你的代码永远不会结束......因为你没有停止条件。此外,您的循环条件不正确。只要运算符是这些值之一,循环就会运行。此外,您永远不会在循环内要求输入。下面的代码应该可以工作:

import java.util.Scanner;


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

int tal1, tal2;
int sum = 0;
int sub=0;
String operator = "";


Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);

System.out.println("write in first digit");
tal1 = input.nextInt();


System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();

System.out.println("Enter + to add and - subtract ");

while (true){

operator = input2.nextLine();
if (operator.equals("+")){
    sum = tal1+tal2;
    System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
    sub = tal1-tal2;
    System.out.println("the subtracted value  is " + sub);

}

if (operator.equals("*") || operator.equals("/")){
    System.out.println("You have put in the wrong operator, your options are + or -");
    break;
  }
  }
 }
}
于 2013-11-02T22:01:11.903 回答