0

我正在尝试创建一个程序,该程序从用户那里获取一个整数值,然后打印计算出的解决方案。更具体地说,将一周的工作时间乘以 regpay,如果工作时间超过 35 小时,则 regpay 乘以 1.5。计算是正确的,我只是无法将小时数输入到输入表单中,以便将其相乘。

我对 Java 完全陌生,并且一直在到处寻找解决方案。非常感谢您的帮助。

这是我到目前为止工作的代码:package chapter1_prog4;

import java.util.Scanner;

/**
*
* @author Brian
*/
public class Chapter1_Prog4 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Scanner userInput = new Scanner(System.in);

    String hours;
    System.out.print("Enter amount of hours worked for the week:");
    hours = userInput.next();

    double regpay, earned, overh;

    regpay = 15;
    earned = 0;
    overh = 0;

    if (hours<=35)
        earned = (hours*regpay);
    else
        overh = ((hours-35)*(regpay*1.5));
        earned = (35*regpay)+overh;

    System.out.println( "Amount earned before taxes: $" + earned);

 }
 }
4

3 回答 3

2

您试图将 a 乘以Stringa double,但这是行不通的。尝试输入其中一种数字类型hours

更改以下部分

String hours;
System.out.print("Enter amount of hours worked for the week:");
hours = userInput.next();

double hours;
System.out.println("Enter amount of hours worked for the week: "); 
hours = userInput.nextDouble();

if语句也有错误

改变

if (hours<=35)
    earned = (hours*regpay);
else
    overh = ((hours-35)*(regpay*1.5));
    earned = (35*regpay)+overh;

if (hours<=35) {
    earned = (hours*regpay);
} else {
    overh = ((hours-35)*(regpay*1.5));
    earned = (35*regpay)+overh;
}

问题是,如果您不将后面的内容ifelse那些花括号括起来,则只会看到每个花括号之后的第一个语句。在上面未更正的例子中,earned = (35*regpay)+overh;总是会被计算,因为它不在else语句的范围内

于 2013-09-07T22:37:05.103 回答
0

如前所述,用户的输入是一个字符串,可以转换为浮点数或整数。这是一个例子:

String hours = "3.2";
int integer = Integer.parseInt(hours);
float floatingPointNumber = Float.parseFloat(hours);

然而,为了安全起见,如果你这样做了,你应该做一个 try-catch,这样如果用户输入的不是数字,你的程序就不会崩溃。这是一个例子:

String test = "r";
try{
int integer = Integer.parseInt(test);
}catch (NumberFormatException e) {
    System.out.println(e);
}
于 2013-09-07T23:14:40.413 回答
0

字符串不能与整数一样使用,在 Java 中以下行无法编译

if ("string" <= 100)

许多解决方案都适用,这是一个

在此行之后:

hours = userInput.next();

添加这一行:

Integer hoursInteger = Integer.valueOf(hours);

并将您的所有引用从几个小时重构为hoursInteger.

于 2013-09-07T22:45:11.370 回答