gpt4 book ai didi

java - 如何根据java中的输入生成计算输出?

转载 作者:行者123 更新时间:2023-12-02 06:45:30 27 4
gpt4 key购买 nike

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

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

这是我迄今为止编写的代码: 包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);

}
}

最佳答案

您正在尝试将 Stringdouble 相乘,但不起作用。尝试输入小时的数字类型之一

更改以下部分

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 语句的范围内

关于java - 如何根据java中的输入生成计算输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678556/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com