Do an integer check without using exceptions

78 views Asked by At

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.");
    }
}

}

2

There are 2 answers

0
Elliott Frisch On

You should call Scanner.hasNextInt() before calling Scanner.nextInt(). Likewise with Scanner.hasNext() and Scanner.next().

2
DoubleDouble On

You are showing a lot of misunderstandings with this one line

if (a = char || b = char)
  1. I assume you mean to use the equal to operator, rather than the assignment operator == instead of =

  2. a and b (and c) are ints, as declared in main. So we know they will never be chars, 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.

  3. 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.