扫描仪输入中不能使用小数

时间:2016-12-08 13:05:13

标签: java

我这里有这个代码:

import java.util.Scanner;

public class Loan {
public static void main(String[] args) {
  Scanner input = new Scanner(System.in);

  System.out.print("Enter annual interest rate, e.g., 7.35%: ");
  double annualInterestRate = input.nextDouble();

  double monthlyInterestRate = annualInterestRate / 1200;

  System.out.print("Enter number of years as an integer, e.g., 5: ");
  int numberOfYears = input.nextInt();

  System.out.println("Enter loan amount, e.g., 120000.95:" );
  double loanAmount = input.nextDouble();

  double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow
          (1 + monthlyInterestRate, numberOfYears * 12));

  double totalPayment = monthlyPayment * numberOfYears * 12;

  System.out.println("The monthly payment is $" + 
    (int)(monthlyPayment * 100) / 100.0);
  System.out.println("The total payment is $" + 
    (int)(totalPayment * 100) /100.0);

   }
}

annualInterestRate是一个double值但是当我尝试输入像5.4这样的小数时,我得到一个错误。使用整数可以很好地完成。 代码有什么问题吗?感谢:)

1 个答案:

答案 0 :(得分:0)

您的语言环境(挪威)使用,作为小数分隔符,因为它在the list of Oracle中指定,如下所示:

  

4.294.967.295,000

正如文件所述:

  

扫描程序的初始区域设置是Locale.getDefault()

返回的值

但您可以使用Scanner更改useLocale(Locale)区域设置,如下所示:

Scanner sc = new Scanner(ystem.in);    
sc.useLocale(Locale.ENGLISH);

如文件所述

  

可以通过useLocale(java.util.Locale)方法

进行更改

这将接受.作为分隔符。

The full documentation is here