Try this:
import java.util.Scanner;
public class SimpleCalculatorScanner {
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
String[] variables = sc.nextLine().split(" ");
int a = 0;
int b = 0;
int c = 0;
int d = 0;
for(int i = 0; i < variables.length; i++) {
try {
if(variables[i].substring(0, 2).equals("a=")) {
a=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("b=")) {
b=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("c=")) {
c=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("d=")){
d=Integer.parseInt(variables[i].substring(2));
}else {
System.out.println("Unrecognized variable "+variables[i].substring(0, 1)+" detected");
return;
}
}catch(NumberFormatException e) {
System.out.println("The character you assigned to variable "+variables[i].substring(0, 1)+" isn't a number");
return;
} }
if (a < b){
System.out.printf("%d", a * c);
}
if (a == b){
System.out.printf("%d", a * c);
}
if (a > b){
System.out.printf("%d", a * d);
}
}
}
Sample I/O
Input
b=5 d=10 a=10 c=4
Output
100
Input 2
b=5 d=10 e=10 c=4
Output 2
Unrecognized variable e detected
Input 3
a=10 b=5 c=4 d=iforgot
Output 3
The character you assigned to variable d isn't a number
How it works
The Scanner reads a new line, and then turns it into an array by splitting every space.
Once the variables have been stored into an array, we run a for loop to test whether the first 2 characters of each item of the array are a=
, b=
, c=
or d=
. If it is a=
, then it parses the every character after the =
of the item in the array into an integer, and assigns it to variable a, vice versa.
If it doesn't recognize the variable, it will print Unrecognized variable <variablename> detected
.
If the character assigned to the variable wasn't a number, it will print The character you assigned to variable <variablename> isn't a number