0

I need the input to be only a float. When I enter a char, a String or a number with a point (100.96 instead of 100,96) the program spams messages. I've added the .hasNextFloat() but nothing chaneged. Any suggestion? Thank you.

boolean prosegui = false;
while (!prosegui) {
    System.out.print("Digitare il proprio saldo in euro (€): ");
    // Se si vuole inserire un saldo che comprende i decimali bisogna utilizzare la virgola.
    if (scanner.hasNextFloat()) {
        saldo = scanner.nextFloat();
        if (saldo > 0) {
            prosegui = true;
        } else
            System.out.println("Il proprio saldo non può essere pari o inferiore a €0.");
    } else {
        System.out.println("Il saldo immesso non è valido.");
        System.out.println("Immettere un saldo valido.");
    }
}
  • 1
    This code seems malformed. I see two nested elses that appear to be at the same level, but aren't actually. Can you reformat? It's also likely you aren't clearing the buffer a la https://stackoverflow.com/questions/26446599/how-to-use-java-util-scanner-to-correctly-read-user-input-from-system-in-and-act – Compass Mar 09 '20 at 19:03
  • @Compass Yeah sorry, my bad. Now it should be formatted correctly. What do you mean with "you aren't clearing the buffer"? – G. Pasquini Mar 10 '20 at 08:13

1 Answers1

1

When you enter something that cannot be converted to float, you get proper Exceptions. You can catch them:

boolean prosegui = false;
while (!prosegui) 
{
    System.out.print("Digitare il proprio saldo in euro (€): ");
    try
    {   
        saldo = scanner.nextFloat(); 
        if (saldo > 0) 
        {
            prosegui = true;
        } 
        else
        {
            System.out.println("Il proprio saldo non può essere pari o inferiore a €0.");
        }   
    }
    catch (Exception e)
    {
        System.out.println("Il saldo immesso non è valido.");
        System.out.println("Immettere un saldo valido."); 
        scanner.nextLine(); // clear bad input
    }  
}
Stefan
  • 1,789
  • 1
  • 11
  • 16
  • Thank you very much Stefan, it solved my problem! But now a doubt arises.Why, when I try to enter a float with a point (not with a comma), it says that it's not valid? – G. Pasquini Mar 10 '20 at 08:18
  • @G.Pasquini: Your default Locale specifies a comma rather than a period for a decimal point. You could do a search / replace for a period decimal point before you try and convert the String into a float or double. – Gilbert Le Blanc Mar 10 '20 at 10:02