-2

I started learning java recently

My problem is if I use static Scanner read= new Scanner(System.in); and when I enter s1 value non-integer I'm getting this error:

Exception in thread "main" java.util.InputMismatchException at this line:

a = oku.nextInt(); in goster() method.

When I remove static Scanner read= new Scanner(System.in); and activate commented line in goster() method everything works fine.

What changes when I use static that causes my code to fail?

public static void main(String[] args) {

        while (check)
        {
            goster();
            try
            {
                hatali=false;
                System.out.print("1. sayi: ");
                s1 = read.nextDouble();
                System.out.print("2. sayi: ");
                s2 = read.nextDouble();
    

                
            } catch (Exception e)
            {
                System.out.println("HATALI SAYI GİRİŞİ!");
                hatali=true;
            }
            
            if(hatali==false)
            {
            menu(a, s1, s2);
            }
        }

 public static void goster() {
       //Scanner read= new Scanner(System.in);
        System.out.println("");
        System.out.println("1- a+b");
        System.out.println("2- a-b");
        System.out.println("3- a*b");
        System.out.println("4- a/b");
        System.out.println("5- a%b");
        System.out.println("6- a^b");
        System.out.println("7- cikis");
        System.out.print("seciminiz 1-7: ");
        a = read.nextInt();
    }
Community
  • 1
  • 1
simonsays
  • 1
  • 4
  • Sounds like possibly a duplicate of http://stackoverflow.com/questions/14027537/input-mismatch-exception - Shouldn't the input "s1" throw that execption as it's not an int, and you're calling `nextInt` ? – Andy Hoffner May 26 '15 at 22:28
  • When I enter non integer `s1` gives output message and program continues. It gives `a` my last input value and since i dont use try-catch for `a=read.nextint()` code fails. But if i use scanner inside methods instead of using static scanner at the beginning, it works fine because program asks me `a` value again instead of using my non-integer input from `s1 = read.nextDouble(); `line – simonsays May 27 '15 at 09:22

1 Answers1

0

nextInt() is used to "Scan the next token of the input as an int". If you want the input to be of general type, nextByte().

Ramzy
  • 6,948
  • 6
  • 18
  • 30