编写一个读取两个浮点数的Java程序,并测试它们是否相同,最多三位小数

时间:2017-06-28 10:11:48

标签: java

为什么我的流程将成为if语句的其他部分

公共类Exercise6MatchDecimalValues {

    public static void main(String[] args) throws Exception
    {
        Scanner stream = new Scanner(System.in);
        System.out.println("Input floating point number: ");
        Double input1= stream.nextDouble();
        System.out.println("Input another floating point number: ");
        Double input2 = stream.nextDouble();
        String input1StringDecimal = String.valueOf(input1).split("\\.")[1].substring(0, 3);   //To get the first 3 decimal values
        String input2StringDecimal= String.valueOf(input2).split("\\.")[1].substring(0, 3);  //To get the first 3 decimal values
        String input1StringWhole=String.valueOf(input1).split("\\.")[0];  //To get the whole value
        String input2StringWhole=String.valueOf(input2).split("\\.")[0]; // //To get the whole value
        System.out.println("input1StringWhole"+input1StringWhole);
        System.out.println("input1StringDecimal"+input1StringDecimal);
        System.out.println("input2StringWhole"+input2StringWhole);
        System.out.println("input2StringDecimal"+input2StringDecimal);

        if(input1StringDecimal == input2StringDecimal && input1StringWhole==input2StringWhole) {
            System.out.println("They are same");
        }else
        {
            System.out.println("They are different! ");
        }

    }

}

Input floating point number: 123.1234

输入另一个浮点数:123.1234

input1StringWhole 123

input1StringDecimal 123

input2StringWhole 123

input2StringDecimal 123

他们是不同的!

2 个答案:

答案 0 :(得分:1)

浮动23232.231231四舍五入为23232.23

因此,如果将该float转换为字符串并取小数点后的部分,则只有两个字符长,substring(0,3)会引发异常。

答案 1 :(得分:0)

使用double然后它应该工作。你给浮动的双倍价值,因此它会变得圆润。