输入小数时,为什么它会给我错误?

时间:2015-09-24 02:40:00

标签: java

抱歉,这是我编程的第一周,我的任务是根据用户输入设计一个计算常规工资和加班费的程序,但是当我按小时或费率计算5.5时,它会给我带来错误。真的明白为什么

如果有办法修复错误,那么如何在输出整数末尾摆脱.0?感谢一帮,老师只是假设我们在服用AP CS时知道所有的东西,这是去年的评论和#34;介绍课程"所以我有点不知所措,如果还有一些时间,请你解释背后的机制" double"?到目前为止我的理解意味着你可以使用小数而不是int,你只能在这里放置整数代码

`

import javax.swing.JOptionPane;

public class Salary
{
    public static void main(String[] args)
    {
        String s1, s2;
            double number1, number2;

            s1=JOptionPane.showInputDialog("Enter the number of hours worked");
            s2=JOptionPane.showInputDialog("Enter the rates per hour");

            number1 = Integer.parseInt ( s1); 
            number2 = Integer.parseInt ( s2); 

            double elseregularp = ( 40*number2);
            double regularp = ( number1*number2);
            double othours = (number1-40);
            double othourspay = ( number2* 15/10.0);


            if( number1 <= 40)
            {
                System.out.println("YOU WORKED "+number1+" HOURS" );
                System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
            }
            else 
            {
                System.out.println("YOU WORKED " + number1+" HOURS");
                System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
                System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
                System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
            }
    }
}

`

1 个答案:

答案 0 :(得分:0)

integer.parseInt(...)接受的字符串值不是正确的输入。因此将其更改为parseDouble以使其正常工作。

修改后的最终代码。

integer.parseInt(...)更改为Double.parseDouble(...)

import javax.swing.JOptionPane;

public class Salary
{
    public static void main(String[] args)
    {
        String s1, s2;
        double number1, number2;

        s1=JOptionPane.showInputDialog("Enter the number of hours worked");
        s2=JOptionPane.showInputDialog("Enter the rates per hour");

       // number1 = Integer.parseInt ( s1); 
       // number2 = Integer.parseInt ( s2); 
        number1=Double.parseDouble(s1);
        number2=Double.parseDouble(s2);
        double elseregularp = ( 40*number2);
        double regularp = ( number1*number2);
        double othours = (number1-40);
        double othourspay = ( number2* 15/10.0);


        if( number1 <= 40)
        {
            System.out.println("YOU WORKED "+number1+" HOURS" );
            System.out.println("YOU EARNED $"+number1 * number2+" REGULAR PAY");
        }
        else 
        {
            System.out.println("YOU WORKED " + number1+" HOURS");
            System.out.println("YOU EARNED $"+elseregularp+" REGULAR PAY");
            System.out.println("AND $" +(othours)*(othourspay)+ " IN OVERTIME");
            System.out.println("YOUR TOTAL CHECK IS $" + ((elseregularp)+(othours)*(othourspay)));
        }
}

}