Why is nextDouble() from the Scanner method sending me “Exception”

前端 未结 2 448
小蘑菇
小蘑菇 2021-01-26 03:37

I\'m suppose to enter 2 numbers, one int that is the amount to withdraw and one double which is the balance (with a space between them). Since every withdraw charges a fee of 0.

相关标签:
2条回答
  • 2021-01-26 04:02

    You can check, if there is some int or double to read. And you have to use , or . depending on the country, you are. If you need it country independent, read it as string and parse then (see below)

    A solotion would be to read the line as a string and parse it then to int and double.

    Checking if double is available:

    input.hasNextDouble();
    

    Read as String:

    String line = input.nextLine();
    String[] sl = line.split(" ");
    amount = Integer.parseInt(sl[0]);
    balance = Double.parseDouble(sl[1]); //solve the problem with . and ,
    

    You also could check if there are enough inputs.

    0 讨论(0)
  • 2021-01-26 04:12

    It is dependant on Locale, try to use comma instead of a dot or vice versa.

    Ex: 1,5 instead of 1.5

    0 讨论(0)
提交回复
热议问题