Java:我的循环永远不会结束,有没有更聪明的方法来编码它

Java:我的循环永远不会结束,有没有更聪明的方法来编码它,java,if-statement,nested,Java,If Statement,Nested,这个想法是,如果他们选择了*如果他们会说错误的运算符,请再试一次,但现在只是循环如果我选择了错误的运算符,并且如果我选择了正确的运算符,程序需要结束,我似乎无法理解 我的代码如下 import java.util.Scanner; public class Uppgift5 { public static void main (String[] args){ int tal1, tal2; int sum = 0; int sub=0; String

这个想法是,如果他们选择了*如果他们会说错误的运算符,请再试一次,但现在只是循环如果我选择了错误的运算符,并且如果我选择了正确的运算符,程序需要结束,我似乎无法理解

我的代码如下

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

}
}
}

您的操作员永远不会与众不同。因此,循环永远不会结束。您应该使用if而不是while

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

您的问题在于:

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

假设
运算符
+
操作符
的值在
while
循环中不会改变,因此
操作符
将始终是
+
,并且您有一个无限循环。

当然,您的代码永远不会结束。。。因为你没有停止的条件。此外,您的循环条件不正确。只要操作符是这些值之一,循环就会运行。此外,您从不在循环中请求输入。下面的代码应该有效:

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