I have been working with Java for a very short time, so please be patient with me. I'm working on a program for an INTRODUCTION to java class and I have to create a simple calculator (no GUI) without using exceptions, but that still captures input errors. I was able to do the exception handler with no problem, but this one is driving me bonkers!! I need an alternative to the statement "if (a==char || b==char)" Here's what I have so far:
import java.util.*;
public class calculator_No_Event {
public static void main(String[] args)
{
// TODO Auto-generated method stub
int a,b,c;
char d;
boolean e;
Scanner input=new Scanner(System.in);
try
{
System.out.print(" Enter the first number: ");
a=input.nextInt();
System.out.print("Enter the second number: ");
b=input.nextInt();
System.out.print("Enter + or - :");
String f=input.next();
d=f.charAt(0);
if (a==char || b==char)
{
System.out.println("Error");
}
else
{
switch(d)
{
case '+':
c =a+b;
System.out.print(a + "+" + b + "=" + c);
break;
case '-':
c =a-b;
System.out.print(a + "-" + b + "=" + c);
break;
}
}
}
finally
{
System.out.println("Thank you.");
}
}
}
You should call
Scanner.hasNextInt()
before callingScanner.nextInt()
. Likewise withScanner.hasNext()
andScanner.next()
.