Java - Scanning comma delimited double and int values

十年热恋 提交于 2019-12-01 20:51:37

Most likely you have Locale issues and your Scanner tries to parse doubles with comma delimeter, but you set comma as a scanner delimeter. Try the following solution:

Scanner input = new Scanner(System.in)
        .useDelimiter(",")
        .useLocale(Locale.ENGLISH);

This will set doubles delimiter to dot and your comma-separated doubles should work fine.

Be sure to place the comma at the end of input to parse the last value, e.g. 1000.00,3.25,5, (may be even it is the primary reason of your inputs not working)

Eduardo Dennis

The issue you faced is because nextDouble() doesn't consume the last line. Try adding an input.nextLine() at the end it should work as expected.

   /* Enter your code here. Read input from STDIN. Print output to STDOUT */
System.out.print("Enter your values: ");
Scanner input = new Scanner(System.in).useDelimiter(",");

double investmentAmount = input.nextDouble();
double monthlyInterestRate = input.nextDouble() / 100 / 12;
double numberOfYears = input.nextDouble();
input.nextLine();
double duration = numberOfYears * 12;

double futureInvestmentValue = investmentAmount * Math.pow((1 + monthlyInterestRate), duration);
System.out.println(investmentAmount);
System.out.println(monthlyInterestRate);
System.out.println(numberOfYears);
System.out.println(duration);
System.out.println("Accumulated value is " + futureInvestmentValue);

Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

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