-2

How do I check if a variable is equal or not equal to a contains? I want to make it so if someone where to put in an invalid operator it would say try again.

String operator = "+, -, *,/, %";
double num1, num2, sum=0;    
System.out.println("First number: ");
num1 = input.nextDouble();
System.out.println("Second number: ");
num2 = input.nextDouble();
if (operator.contains("+")){
    sum = num1 + num2;
} else if (operator != operator.contains("+,-,*,/,%"){

System.out.println("Error"); }

Cmi
  • 479
  • 2
  • 5
  • 12
  • I think he means 'operator'? Still doesn't make a lot of sence – n247s Oct 25 '16 at 20:55
  • @MaxZoom Like is there a way to check if my contains is == to my operator? – Cmi Oct 25 '16 at 21:01
  • @Cmi Please [edit] your question to be more clear and detailed about what you're trying to accomplish. In the code you're showing, the "if" statement will always execute because `operator` is always "+, -, *,/, %"; – Brian Oct 25 '16 at 21:04
  • @Brian I know but how do I make it so when a user enters in like 7 as an op it gives an error? – Cmi Oct 25 '16 at 21:06
  • Possible duplicate of [how to check if string contains '+' character](http://stackoverflow.com/questions/10060804/how-to-check-if-string-contains-character) – Lolmewn Oct 25 '16 at 21:07
  • @Cmi the else if is not even correct statement. contains returns boolean and you are comparing it to a string – Nick Div Oct 25 '16 at 21:10
  • @NickDiv I am not good in java so my mistake. Would I have to make it == to a boolen either true or false? – Cmi Oct 25 '16 at 21:12
  • @Cmi I would guess you are trying something like this: Scanner sc=new Scanner(System.in); System.out.println("First number: "); num1 = sc.nextDouble(); System.out.println("Select the operation"); String operation = sc.next(); System.out.println("Second number: "); num2 = sc.nextDouble(); if (operator.contains(operation)){ sum = num1 + num2; System.out.println(sum); } – Nick Div Oct 25 '16 at 21:16

1 Answers1

1

If you want to check what operator should be used based on the user entry, you could use switch statement as below

String operator = "";
while (operator.isEmpty()) {
  System.out.println("Enter Operator: ");
  operator = input.next();
  switch (operator) {
    case "+" : result = num1 + num2; break;
    case "-" : result = num1 - num2; break;
    case "*" : result = num1 * num2; break;
    case "/" : result = num1 / num2; break;
    default  : System.out.println("Invalid operator: " + operator);
               operator = "";
  }
  System.out.println("Result is " + result);
}

DEMO

If you only want to check if the operator is valid, you can use List contains() method:

String[] operators = { "+", "-", "*", "/" , "%" };
List<String> ops = Arrays.asList(operators);
:
System.out.println("Enter Operator: ");
String operator = input.next();
if (ops.contains(operator)) {
   // do some calculation here
}
MaxZoom
  • 7,619
  • 5
  • 28
  • 44