整個代碼非常簡單,從以前的項目我們或多或少地將其轉換爲使用方法。基本上它會提示用戶輸入他們的姓名,工作時間以及工資率,然後將這些信息計算爲淨工資。我已經寫了大部分的代碼,並從我的理解,它工作正常。Java方法,打印歡迎信息,然後感謝您的信息
現在我的問題。一種方法必須在屏幕上打印消息,我必須在程序開始時調用一次方法來打印歡迎消息,並在程序結束時打印「謝謝」消息。因此,我迷失於如何使它成爲可能,因此單一方法可以確定它何時結束程序。 (當用戶輸入一個-1提示輸入自己的名字時,該程序將結束。)
package project.pkg2;
import java.util.*;
public class Project2 {
// Scanner for the console inputs
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
String name, formatNet;
double hours, pay, netPay;
// Prints the welcome message from the method.
welcomeMessage();
// Every initialized variable receives the return statements from their respected methods.
name = getName();
while (!(name.equals("-1")))
{
pay = getPay();
hours = getHours();
netPay = calcNet(pay,hours);
// Formats the net pay to be 2 decimals.
formatNet = String.format("%.2f", netPay);
System.out.println(name + "'s net pay is $" + formatNet + " \n");}
// Method for the welcome message, a void because it returns no values.
}
static void welcomeMessage()
{
System.out.println("Welcome to the CIS 220 Payroll Calculator!\n");
}
// Method that prompts the user to enter their name, scans it, then returns it.
static String getName()
{
String name;
System.out.println("Please enter the employee's name(Enter a -1 when finished): ");
name = console.nextLine();
return name;
}
//Method that prompts the user to enter their pay rate, scans it, then returns it.
static double getPay()
{
double payRate;
System.out.println("Please enter the employee's pay rate: ");
payRate = console.nextDouble();
console.nextLine();
return payRate;
}
//Method that prompts the user to enter their hours worked, scans it, then returns it.
static double getHours()
{
double hours;
System.out.println("Please enter the employee's hours worked:");
hours = console.nextDouble();
console.nextLine();
return hours;
}
//Method that uses the pay rate, hours worked that the user has entered.
//determines if the user qualifies for overtime pay or not, then calculates the overall pay
//followed by tax reduction, then returns the netpay value.
static double calcNet (double pay, double hours)
{
double net, grossPay;
String formatNet;
if(hours > 40)
{
grossPay = (pay * hours) * 1.5;
}
else
{
grossPay = pay * hours;
}
net = grossPay - (grossPay * .15);
return net;
}
}
「謝謝」不是「歡迎」。聽起來很凌亂 – Bohemian
@Bohemian - 重命名該方法。 – Jason
我想你已經回答了這個問題。我沒有看到練習的要點:/ – Bohemian