Java能够选择是添加还是减去

时间:2013-11-02 21:27:00

标签: java if-statement

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

第二个问题是我需要创建一个永无止境的循环是否有比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 -");
}

}

}

3 个答案:

答案 0 :(得分:1)

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

operator = input.nextLine();

所有内容都是新行字符。您需要添加额外的

nextLine();

nextInt()后调用,以便它可以使用danglign \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();

答案 1 :(得分: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

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

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