如何输入两位十进制数

时间:2014-09-25 15:36:30

标签: java floating-point decimal

import java.text.DecimalFormat;
import java.util.Scanner;


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

    double number1;
    double number2;
    double number3;

    System.out.print("Insert first number:");
    number1=input.nextInt();

    System.out.print("Insert second number:");
    number2=input.nextInt();

    System.out.print("Insert third number:");
    number3=input.nextInt();

    DecimalFormat df = new DecimalFormat("0.00");

    System.out.println(df.format(number1));
    System.out.println(df.format(number2));
    System.out.println(df.format(number3));
}}

当我插入第一个数字时,例如:

Insert first number:1

它将打印出1.00

如果我插入数字Insert first number:1.00,我会收到错误。如何插入带小数点的数字?

2 个答案:

答案 0 :(得分:1)

你写了number1=input.nextInt();但是“1.00”不是int;这是双倍的。请改为number1=input.nextDouble();

答案 1 :(得分:1)

试试这个: number1 = input.nextDouble();