-1

我有两个问题,首先是为什么我不能添加运算符,我可以添加第一个和第二个整数但不能添加运算符。

第二个问题是我需要创建一个永无止境的循环,有没有比 while 循环更简单的方法?基本上的想法是,例如,如果他们选择 * 如果会说错误的运算符,请再试一次

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

    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 = input.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);

    }

    System.out.println("You have put in the wrong operator, your options are + or -");
}

}

}

4

3 回答 3

1

nextInt方法不会使用您在键盘上按回车键时输入的空白​​字符(换行符)。当你然后打电话

operator = input.nextLine();

读取的只是换行符。您需要添加一个额外的

nextLine();

在 the 之后调用,nextInt()以便它可以使用 dangign \n(或\r\n取决于您的系统)字符。

Scanner input = new Scanner (System.in);

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

System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
input.nextLine();
System.out.println("Enter + to add and - subtract ");
operator = input.nextLine();
于 2013-11-02T21:29:52.267 回答
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-03T14:47:34.837 回答
0

要创建一个将一直运行直到提供有效输入并且与您的while构造不同的循环,请尝试以下几行:

String input;
do {
    input = getInput(); //Replace this with however you get your input
} while(!(input.equals("+") || input.equals("-")));

但是,如果您希望通知用户,您将需要使用while类似于您现在的循环。Java 中的循环类型并不多,而且while循环非常简单。一段通知用户的代码可以如下所示:

String input;
while(true) {
    input = getInput();
    if(input.equals("+") || input.equals("-")) break; //Exit loop if valid input
    System.out.println("Invalid input");
}

//Do arithmetic here

至于您的第一个问题,我并不完全清楚您所说的“添加运算符”是什么意思。你能澄清一下吗?

于 2013-11-02T21:44:17.087 回答