I am making a program that takes a user input of two doubles and an operator, and performs a calculation. For example, if the user inputs "12 - 6", the result will be 6. It also works if the user inputs "12 6 -". I am trying to create an error check that checks if there is either not enough tokens, or too many tokens. How do I do this?
double num1, num2;
String operator ;
DecimalFormat decPattern = new DecimalFormat("#.00");
System.out.println("");
Scanner scan = new Scanner(System.in);
System.out.print("Please enter two operands and an operator > ");
if (scan.hasNextDouble())
{
num1 = scan.nextDouble();
if (scan.hasNextDouble())
{
num2 = scan.nextDouble();
operator = scan.next();
scan.close();
}
else
{
operator = scan.next();
num2 = scan.nextDouble();
scan.close();
}
}
else
{
operator = scan.next();
num1 = scan.nextDouble();
num2 = scan.nextDouble();
scan.close();
}
System.out.println("");
calc(operator, num1, num2);
}