I have two question, first is why cant I add an operator , I can add first and 2nd integer but not an operator.
2nd question is I need to create a never ending loop is there an easier way than the while loop? basically the idea is that if for example they choose * if will say wrong operator please try again
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 -");
}
}
}
解决方案
The nextInt method does not consume the whitespace characters (newline) that you input when you press the carriage return on your keyboard. When you then call
operator = input.nextLine();
All that reads is that new line character. You need to add an extra
nextLine();
call after the nextInt() so that it can consume the danglign \n (or \r\n depending on your system) character.
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();