Java:我的循环永远不会结束,并且有一种更聪明的方式来编码它

时间:2013-11-02 21:48:10

标签: 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 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 个答案:

答案 0 :(得分:2)

你的问题在这里:

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

假设operator+operator的值while不会在operator循环中发生变化,因此+始终为{{1}},并且您的循环无限。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用在您从输入中读取while之前开始的do loop而不是使用operator循环,而只有在operator不是+时才会循环回来}或-。理想情况下,while循环末尾的do应该在您尝试计算之前出现。

答案 3 :(得分: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;
  }
  }
 }
}