Java – 扫描逗号分隔的double和int值

我正在尝试使用Java的Scanner类来扫描用逗号分隔的double和int值。

以下Scanner input = new Scanner(System.in).useDelimiter("\\D"); 只能扫描由…分隔的int值。 例如输入= 1000,2,3

如何扫描由…分隔的double和int值,例如input = 1000.00,3.25,5100.00,2,3.5

我尝试了以下但它们似乎不起作用:

 Scanner input = new Scanner(System.in).useDelimiter(","); Scanner input = new Scanner(System.in).useDelimiter("\\,"); Scanner input = new Scanner(System.in).useDelimiter("[,]"); 

使用这些似乎挂起代码。 输入示例输入后,System.out.println未针对已扫描的变量执行。

以下是我的示例代码:

 import java.io.*; import java.util.Scanner; public class Solution { public static void main(String args[] ) throws Exception { /* 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("\\D"); Scanner input = new Scanner(System.in).useDelimiter(","); // Scanner input = new Scanner(System.in).useDelimiter("\\,"); // Scanner input = new Scanner(System.in).useDelimiter("[,]"); double investmentAmount = input.nextDouble(); double monthlyInterestRate = input.nextDouble() / 100 / 12; double numberOfYears = input.nextDouble(); 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 input = new Scanner(System.in).useDelimiter("[,\n]"); 

很可能您有Locale问题,而您的Scanner尝试使用逗号分隔符解析双打,但您将逗号设置为扫描仪分隔符。 尝试以下解决方案:

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

这会将双打分隔符设置为点,并且逗号分隔的双精度数应该可以正常工作。

请务必将逗号放在输入的末尾以解析最后一个值,例如1000.00,3.25,5, (甚至可能是您输入无法工作的主要原因)

您遇到的问题是因为nextDouble()不消耗最后一行。 尝试添加一个input.nextLine(),它应该按预期工作。

  /* 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); 

在使用next(),nextInt()或其他nextFoo()方法后,Scanner正在跳过nextLine()