0

im beginner in java programing, have task need to be completed and looking for some useful tips. writing program which requires from user correct Float input, if input is incorrect, program gives another chance until correct input, my problem is next, when i enter incorrect input it runs non stop,, any ideas?

   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    float f = 0;
    int x = 1;
    do {
        try {
            System.out.print("Enter an float:");
            f = in.nextFloat();
            x =2;

        } catch (InputMismatchException e) {
            System.err.println("Incorrect entry.");

        }
        System.out.println("Your entry is:" + f);

    }
    while(x==1);
}
George Weekson
  • 484
  • 3
  • 12

2 Answers2

1

Do this and you will get the output you want from your program

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        float f = 0;
        int x = 1;
        do {
            try {
                System.out.print("Enter an float:");
                f = in.nextFloat();
                x = 2;

            } catch (InputMismatchException e) {
                System.err.println("Incorrect entry.");
                in.next();

            }

        } while (x == 1);
        System.out.println("Your entry is:" + f);

    }

You just need to add in.next() in catch block to continue the process.

Abhishekkumar
  • 1,044
  • 7
  • 21
1

As an alternative to the accepted answer, you may want to :

1) Check that the next token is a float hasNextFloat()

2) If it isn't, swallow the whole line nextLine()

 Scanner in = new Scanner(System.in);
        float f = 0;
        String entry;
        int x = 1;
        do {

            System.out.print("Enter an float:");

            if (in.hasNextFloat()) {

                f = in.nextFloat();
                entry = Float.toString(f);
                x = 2;

            } else {

                entry = in.nextLine();
                System.err.println("Incorrect entry.");

            }
            System.out.println("Your entry is: " + entry);

        } while (x == 1);

This has the advantage of getting rid, of wrong input line having multiple tokens (e.g : "aa bb cc").

Arnaud
  • 16,319
  • 3
  • 24
  • 39