0
Validating math operation from user input
I'm working on a project that asks the user for three variable: 2 integers and 1 math operator char of +-*/ or %. How can I validate the char input as one of the 5 signs? I'm at an impass in my if loop because of all the different conditions: public static double compMath(int num1, char operator, int num2) { double result; if (operator == '+'||'-'||'*'||'/'||'%') { System.out.println("Math time!"); //performs appropriate math operation (num1,operator,num2) and returns double result (round to 2 decimal places if necessary (format so no decimal is shown unless needed) } else { System.out.println("I only know how to do +, -, *, /, or %"); } return result; }
1 Odpowiedź
0
full code if curious:
import java.util.Scanner;
public class Jeff_McCann_CIS106_HYB1_ComputerMath {
	public static double compMath(int num1, char operator, int num2) {
		
		double result;
		
		if (operator == '+'||'-'||'*'||'/'||'%') {
			System.out.println("Math time!");
//performs appropriate math operation (num1,operator,num2) and returns double result (round to 2 decimal places if necessary (format so no decimal is shown unless needed)
		} else {
			System.out.println("I only know how to do +, -, *, /, or %");
		}
		
		return result;
	}
	
	public static void main(String[] args) {
		
		Scanner kb = new Scanner(System.in);
		
		System.out.print("Enter integer #1: ");
		int input1 = kb.nextInt();
		
		System.out.print("Enter integer #2: ");
		int input3 = kb.nextInt();
		
		System.out.print("Which operation? (+-*/%): ");
		char input2 = kb.next().charAt(0);
		
		double result = compMath(input1, input2, input3);
		
		System.out.println(input1 + " " + input2 + " " + input3 + " = " + result);
		
		
		kb.close();
	}
}



