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

时间:2016-10-13 18:00:19

标签: java regex java.util.scanner delimiter

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

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

如何扫描由,分隔的double和int值,例如输入= 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]");

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

您面临的问题是因为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);

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