我正在学习Java的第3周,我刚刚提交了一份薪资计算申请表。作为一个极端的新手,我知道我的代码可能很可怕,并会给一个经验丰富的程序员一个偏头痛 - 但这就是我在这里的原因。这项任务已经上交,所以我不是在寻找任何人为我做我的工作,我只是想知道我的代码中的一些具体事情,以及可能是一些一般&# 34;你应该这样做"反馈,如果有人愿意帮助一个有3周经验的人变得更好。
首先,这是我的代码:
// Payroll.java
// This program calculates an employee's net pay
// minus Federal tax (11% off the gross) with Overtime
// Daniel Zaleski
// 08/17/2014
/** Import Scanner */
import java.util.Scanner; // Scanner to read user input
/** Create Class */
public class Payroll // Class declaration
{
public static double hoursWorked; // Declare hoursWorked as a double
public double hoursWorked()
{
return hoursWorked;
}
public static double hourlyRate; // Declare hourlyRate as a double
public double hourlyRate()
{
return hourlyRate;
}
private double taxedPay; // Declare taxedPay as a double
public double taxedPay()
{
return taxedPay;
}
private double netPay; // Declare netPay as a double
public double netPay()
{
return netPay;
}
private static double grossPay; // Defining variable grossPay
private static double overtimePay; // Defining variable overtimePay
private static double overtimeHours; // Defining variable overtimeHours
public static void main(String[] args) // Main method
{
int i = 8; // Setting the application loop
while(i < 9) // Setting the termination variable which doesn't exist to continue loop
{
Scanner input = new Scanner(System.in); // Creating the scanner
/** Prompt for first name */
String firstName; // Variable for the first name
System.out.println("\nEnter Your First Name: (Enter the name quit (all lowercase) to terminate application)\n");
firstName = input.next();
// Setting the loop termination variable "quit"
if(firstName.equals("quit"))
{
System.out.println("You have terminated the Application. Have a nice day.\n");
break;
}
/** Prompt for last name */
String lastName; // Variable for the last name
System.out.println("\nEnter Your Last Name:\n ");
lastName = input.next();
String completeName; // Setting the full name
completeName = firstName + " " + lastName;
System.out.println("\nHello " + completeName);
/** Prompt for hours worked */
double hoursWorked; // Asking for hours worked
System.out.println("\nPlease Enter Your Hours Worked\n ");
hoursWorked = input.nextDouble();
if(hoursWorked < 0.1)
{
System.out.print("Please Enter a Positive Value\n ");
System.out.println("\nPlease Enter Your Hours Worked (Greater Than 0)\n ");
hoursWorked = input.nextDouble();
}
/** Prompt for hourly rate */
double hourlyRate; // Defining hourlyRate
System.out.println("\nPlease Enter Your Hourly Rate\n ");
hourlyRate = input.nextDouble();
if(hourlyRate < 0.1)
{
System.out.print("Please Enter a Positive Value\n ");
System.out.println("\nPlease Enter Your Hourly Rate (Greater Than 0)\n ");
hourlyRate = input.nextDouble();
}
/** Figure Out Overtime Pay */
if(hoursWorked > 40.1)
{
overtimePay = 1.5 * hourlyRate * (hoursWorked - 40.0); // Figuring overtimePay
}
if(hoursWorked > 40.1)
{
grossPay = hourlyRate * hoursWorked + overtimePay; // Figuring overtime gross
}
else
{
grossPay = hourlyRate * hoursWorked; // Non overtime gross
}
/** Figure Out Overtime Hours */
if(hoursWorked > 40.1)
{
overtimeHours = hoursWorked - 40; // Figuring overtimeHours
}
double federalTax; // Defining the Federal Tax variable
federalTax = .11;
double taxedPay; // Defining the taxedPay variable
taxedPay = federalTax * grossPay;
double netPay; // Defining the netPay variable
netPay = grossPay - taxedPay;
/** System print declarations */
System.out.println("\nHello " + completeName); // Print user name
System.out.println("\nYour Hours Worked this Cycle Are: " + hoursWorked); // Print hours worked
System.out.printf("\nYour Current Hourly Rate is: $%,.2f\n", hourlyRate); // Print and format hourlyRate
if(hoursWorked > 40.0)
{
System.out.printf("\nYour Overtime Hours This Cycle: %.2f\n", overtimeHours); // Print and format hourlyRate
System.out.printf("\nYour Overtime Pay This Cycle: $%,.2f\n", overtimePay); // Print and format hourlyRate
}
System.out.printf("\nYour Gross Pay this Cycle is: $%,.2f\n", grossPay); // Print and format grossPay
System.out.printf("\nThe Federal Tax you Paid this Cycle is: $%,.2f\n", taxedPay); // Print and format taxedPay
System.out.println("\nYour Federal Tax Rate is Currently: (11%)"); // Print Federal tax rate
System.out.printf("\nYour Net Pay for the Cycle is: $%,.2f\n", netPay); // Print and format netPay
System.out.println("\nThe word quit was not detected. Let's do it again!\n"); // Create space to do the loop again
} // End loop while
} // End main method
} // End Payroll class
所以我的具体问题如下:
如果值为<= 0
,我如何编程系统提示重新输入hoursWorked和hourlyRate的循环?我知道我有一次重新推广,但在那之后,该计划只是继续进行。我无法弄清楚如何编程这个循环。
应用程序应无限循环,直到单词&#34;退出&#34;进入。它确实如此,但我知道我使用一个永远不会被证明的变量的方式有点不可思议,因为我从不试图证明它。是接受的做法,还是有更好的方法呢?
我是否正确声明了用户输入变量?它有效......但是我找不到其他人这样做的方式。
那就是它。我知道每个人都很忙,但如果有经验的Java程序员有时间帮助初出茅庐,我会非常感激。谢谢。
答案 0 :(得分:1)
要运行while
循环直到单词quit
,您可以使用
while(true)
{
//your code
if(firstName.equals("quit"))
{
System.out.println("You have terminated the Application. Have a nice day.\n");
break;
}
}
在您/** Figure Out Overtime Pay */
和/** Figure Out Overtime Hours */
中您可以编写更少的代码。看到这个:
/** Figure Out Overtime Hours and Pay */
if(hoursWorked > 40.1)
{
overtimeHours = hoursWorked - 40; // Figuring overtimeHours
overtimePay = 1.5 * hourlyRate *overtimeHours ; // Figuring overtimePay
grossPay = hourlyRate * hoursWorked + overtimePay; // Figuring overtime gross
}
else
{
overtimeHours=0;
overtimePay=0;
grossPay = hourlyRate * hoursWorked; // Non overtime gross
}
另一件事是,如果您为任何类变量编写getter / setter,请尝试遵循此约定
您的代码:
public static double hoursWorked; // Declare hoursWorked as a double
public double hoursWorked() // this is the getter mothod of hoursWorked
{
return hoursWorked;
}
方法名称应该类似于
public double getHoursWorked() // this is the getter mothod of hoursWorked
{
return hoursWorked;
}
答案 1 :(得分:1)
我改变了一些东西并添加了一些东西,它并不完美,但它应该有所帮助。
public class Payroll
{
public double hoursWorked; // should not be static
public double hoursWorked() //should be getHoursWorked() and should have setter
{
return hoursWorked;
}
public Payroll setHoursWorked(double hoursWorked)
{
this.hoursWorked = hoursWorked;
return this; //returning itself instead of 'void' allows method chaining
}
public double hourlyRate; // should not be static
public double hourlyRate() //should be getHourlyRate() and should have setter
{
return hourlyRate;
}
private double taxedPay; // Declare taxedPay as a double
public double taxedPay() //should be getTaxedPay() and should have setter
{
return taxedPay;
}
private double netPay;
public double netPay() //should be getNetPay() and should have setter
{
return netPay;
}
private double grossPay; // should not be static, should have getter/setter
private double overtimePay; // should not be static, should have getter/setter
private double overtimeHours; // should not be static, should have getter/setter
public static void main(String[] args)
{
int i = 8; //you are basically using this variable only as a substitute for "while(true)".
Scanner input = null;
try
{
input = new Scanner(System.in); // should not re-allocate the Scanner each call, it is a resource that is ought to be closed
do // should just use a do-while loop
{
String firstName;
System.out.println("\nEnter Your First Name: (Enter the name quit (all lowercase) to terminate application)\n");
firstName = input.next();
if("quit".equals(firstName)) //this way, the app doesn't crash with NullPointerException if firstName is null
{
System.out.println("You have terminated the Application. Have a nice day.\n");
break;
}
String lastName;
System.out.println("\nEnter Your Last Name:\n ");
lastName = input.next();
String completeName;
completeName = firstName + " " + lastName;
System.out.println("\nHello " + completeName);
PayRoll payRoll = new PayRoll(); //have an actual class for the data instead of using it statically
//...
payRoll.setHoursWorked(input.nextDouble()); //use setters like that, also there is no exception handling in case it's not a double from the input
if(payRoll.getHoursWorked() < 0.1)
{
//...
}
// ...
// print print print print etc
}
while(i < 9); //to be honest, this is not very descriptive, a boolean variable would say more about what is happening here and up to what point it is supposed to run and when this loop should end
}
finally
{
if(input != null)
{
input.close(); // Scanner is a resource that is meant to be closed after usage
}
}
}
}
答案 2 :(得分:1)
您可以使用带有条件的while循环(while hoursWorked&gt; 0)
同样,在'quit'输入的情况下,你可以使用带有break语句的while()循环。 - 即
while(true){doCalculations;如果firstName.equals(“quit”)中断;}
至于变量 - 在类中声明所有字段是私有的是一个好习惯。静态不应该是默认选项,应该用于特殊需要。
由于Java是面向对象语言,试图利用它。使用Payroll类并为每个opeartion创建实例方法 - 如getFirstName(),getLastName(),calculateTax(),printDeclarations()。这样代码将更简单,更易于维护和更易读。下一步是创建单独的类而不是方法 - 如TaxCalculator,DeclarationPrinter等。
此外,尽量避免使用“魔术数字” - 在代码中使用它们并不是一个好习惯。你在不同的地方使用40。如果政府更改了这个号码怎么办 - 您必须在代码中找到所有40个号码。尝试将其声明为常量(最终实例字段)。
尽量不要将字段声明与方法声明混合使用。它更具可读性,可以将它们分开,但顺序相同。你可以通过所有代码坚持使用一种格式化模式。
尝试以下代码,看看它是否更具可读性:
// Payroll.java
// This program calculates an employee's net pay
// minus Federal tax (11% off the gross) with Overtime
// Daniel Zaleski
// 08/17/2014
/** Import Scanner */
import java.util.Scanner; // Scanner to read user input
/** Create Class */
public class Payroll // Class declaration
{
private static final Double NORMAL_WORKING_HOURS = 40d;
private static final Double SOME_FACTOR = 1.5;
private static final Double FEDERAL_TAX = 0.11;
private Scanner input;
private String firstName;
private String lastName;
private String completeName;
private double hoursWorked; // Declare hoursWorked as a double
private double hourlyRate; // Declare hourlyRate as a double
private double taxedPay; // Declare taxedPay as a double
private double grossPay; // Defining variable grossPay
private double netPay; // Declare netPay as a double
private double overtimePay; // Defining variable overtimePay
private double overtimeHours; // Defining variable overtimeHours
public Payroll(Scanner input)
{
this.input = input;
}
public void run()
{
while(true)
{
inputFirstName();
if (firstName.equals("quit"))
{
break;
}
inputLastName();
createUser();
welcomeUser();
inputHoursWorked();
inputHourlyRate();
calculateOvertimeHours();
calculateOvertimePay();
calculateGrossPay();
calculateTaxPay();
calculateNetPay();
printDeclaration();
}
System.out.println("You have terminated the Application. Have a nice day.\n");
}
private void inputFirstName()
{
/** Prompt for first name */
System.out.println("\nEnter Your First Name: (Enter the name quit (all lowercase) to terminate application)\n");
firstName = input.next();
}
private void inputLastName()
{
/** Prompt for first name */
System.out.println("\nEnter Your Last Name\n");
lastName = input.next();
}
private void createUser()
{
completeName = firstName + " " + lastName;
}
private void welcomeUser()
{
System.out.println("\nHello " + completeName);
}
private void inputHoursWorked()
{
System.out.println("\nPlease Enter Your Hours Worked\n ");
hoursWorked = input.nextDouble();
while(hoursWorked <= 0)
{
System.out.print("Please Enter a Positive Value\n ");
hoursWorked = input.nextDouble();
}
}
private void inputHourlyRate()
{
System.out.println("\nPlease Enter Your Hourly Rate\n ");
hourlyRate = input.nextDouble();
while(hoursWorked <= 0)
{
System.out.println("\nPlease Enter Your Hourly Rate (Greater Than 0)\n ");
hourlyRate = input.nextDouble();
}
}
private void calculateOvertimeHours()
{
if(hoursWorked > NORMAL_WORKING_HOURS)
{
overtimeHours = hoursWorked - NORMAL_WORKING_HOURS; // Figuring overtimeHours
}
}
private void calculateOvertimePay()
{
overtimePay = SOME_FACTOR * hourlyRate * (overtimeHours); // Figuring overtimePay
}
private void calculateTaxPay()
{
taxedPay = FEDERAL_TAX * grossPay;
}
private void calculateGrossPay()
{
/** Figure Out Overtime Pay */
if(overtimeHours > 0)
{
grossPay = hourlyRate * hoursWorked + overtimePay; // Figuring overtime gross
}
else
{
grossPay = hourlyRate * hoursWorked; // Non overtime gross
}
}
private void calculateNetPay()
{
netPay = grossPay - taxedPay;
}
private void printDeclaration()
{
/** System print declarations */
System.out.println("\nHello " + completeName); // Print user name
System.out.println("\nYour Hours Worked this Cycle Are: " + hoursWorked); // Print hours worked
System.out.printf("\nYour Current Hourly Rate is: $%,.2f\n", hourlyRate); // Print and format hourlyRate
if(overtimeHours > 0)
{
System.out.printf("\nYour Overtime Hours This Cycle: %.2f\n", overtimeHours); // Print and format hourlyRate
System.out.printf("\nYour Overtime Pay This Cycle: $%,.2f\n", overtimePay); // Print and format hourlyRate
}
System.out.printf("\nYour Gross Pay this Cycle is: $%,.2f\n", grossPay); // Print and format grossPay
System.out.printf("\nThe Federal Tax you Paid this Cycle is: $%,.2f\n", taxedPay); // Print and format taxedPay
System.out.println("\nYour Federal Tax Rate is Currently: (11%)"); // Print Federal tax rate
System.out.printf("\nYour Net Pay for the Cycle is: $%,.2f\n", netPay); // Print and format netPay
System.out.println("\nThe word quit was not detected. Let's do it again!\n"); // Create space to do the loop again
}
public static void main(String[] args) // Main method
{
Scanner input = new Scanner(System.in);
new Payroll(input).run();
} // End main method
} // End Payroll class
输出如下:
输入您的名字:(输入名称quit(全部小写)以终止申请)
米哈尔
输入您的姓氏
Schielmann
HelloMichałSchielmann
请输入工作时间
42
请输入您的每小时费率
250
HelloMichałSchielmann
你的工作时间是这个周期:42.0
您当前的每小时费率为:250,00美元
您的加班时间此周期:2,00
您的加班费此周期:$ 750,00
此周期的总薪酬为:11 250美元
你支付这个周期的联邦税是:$ 1 237,50
您目前的联邦税率:(11%)
您的周期净薪酬为:10美元012,50
未检测到退出一词。我们再来一次!
输入您的名字:(输入名称quit(全部小写)以终止申请)
退出 您已终止该申请。祝你有愉快的一天。
答案 3 :(得分:0)
在你的人类中,不要使用静态变量。
所有实例的静态均值相同。如果您要添加两个人,则两个引用都是相同的值。最新的一个覆盖一切。
你的戒烟方法还可以。它通常是退出你的场景的方式。
基于迭代,请选择以下
while (true) {
if (hoursWorked < 0.1) {
System.out.print("Please Enter a Positive Value\n ");
System.out
.println("\nPlease Enter Your Hours Worked (Greater Than 0)\n ");
hoursWorked = input.nextDouble();
} else
break;
}
答案 4 :(得分:0)
好的,让我们从头开始吧。您正在使用方法来获取变量的值。用于此的惯例是调用方法&#34; get&#34; + variableName。 像这样:
public double getHoursWorked() {
return this.hoursWorked;
}
如果要设置此变量,可以使用相同的约定。你调用函数&#34; set&#34; + variableName。 在您的主要功能中,您应该尝试为您的行为使用其他功能。首先你可以创建一个函数calculatePayroll,在这个函数中你将调用额外的函数来计算所需的东西。转换为函数的部分已由您在commnents中定义。对于&#34; / **计算加班时间* /&#34;你可以创建一个函数:
public double calculateOvertimeHours() {
//do your calculation here
}
如果您的程序无法正常工作,这会将您的代码拆分为一些更容易测试和调试的函数。