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

我的梦境 提交于 2019-12-02 20:06:38

问题


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.5, balance must be a double. And thats what must be printed. I get error at nextDouble, why? I have just 1 month coding, I thought this was going to be a piece of cake, I think BASIC syntax ruined me 30 years ago :(

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    //init variables
    int amount;
    double balance;
    //insert amount and balance
    Scanner input = new Scanner (System.in);
    amount = input.nextInt();
    balance = input.nextDouble();
    //reduce amount+fee from balance
    balance=balance-(amount + 0.50);
    //print new balance
    System.out.print(balance);
    input.close();
}
}

回答1:


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

Ex: 1,5 instead of 1.5




回答2:


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.



来源:https://stackoverflow.com/questions/36912470/why-is-nextdouble-from-the-scanner-method-sending-me-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!