Reputation:
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.");
}
}
}
Upvotes: 0
Views: 67
Reputation: 1493
You are showing a lot of misunderstandings with this one line
if (a = char || b = char)
I assume you mean to use the equal to
operator, rather than the assignment
operator == instead of =
a
and b
(and c
) are int
s, as declared in main
. So we know they will never be char
s, unless you convert them to chars - but then they would always be chars. int
and char
are different types, and the 1
character could be either type - so trying to do it as you are just won't work.
A google search for check if string is number returns Determine if a String is an Integer in Java, However, in this case @ElliottFrisch's answer is the method you probably want to use. Learning to look at the Documentation whenever you use a new Java class (like Scanner) is very valuable and can lead to a lot better understanding and knowledge of the classes you are using.
Upvotes: 0
Reputation: 201537
You should call Scanner.hasNextInt()
before calling Scanner.nextInt()
. Likewise with Scanner.hasNext()
and Scanner.next()
.
Upvotes: 2