【发布时间】:2014-01-14 22:53:57
【问题描述】:
我正在开发一个小型 Java 程序,该程序会向在我学校注册 AP 考试的学生发送收据。代码如下所示。
// Create email text body for student who registered for an AP exam.
import java.util.Scanner;
class EmailText {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String first_name;
String email;
int numTests;
char ch;
char choice;
int cost;
System.out.print("Enter student first name: ");
first_name = input.next();
System.out.print("Enter student email: ");
email = input.next();
System.out.print("Enter number of tests ordered (1-9): ");
numTests = input.nextInt();
if(numTests < 10) {
System.out.print("Did student qualify for fee waiver (y/n)? ");
ch = input.next().charAt(0);
if(ch == 'y') {
cost = 5;
int total = numTests * cost;
System.out.println("** COPY/PASTE THIS DRAFT **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.\n");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
else if(ch == 'n') {
cost = 89;
int total = numTests * cost;
System.out.println("** Copy/Paste this Draft **");
System.out.println("To: " + email);
System.out.println("Subject: 2014 AP Test Receipt for " + first_name);
System.out.println();
System.out.println("Hi " + first_name + ",\n");
System.out.println("Thank you for registering for the 2014 AP Exams!");
System.out.println("According to our records, you ordered " + numTests + " tests.");
System.out.println("Because you stated that you qualified for a fee waiver, " +
"each test will cost you $" + cost + ".");
System.out.println("Your total cost is $" + cost + " * " + numTests +
" = $" + total + ".\n");
System.out.println("Please submit your payment to the College Counseling Office ASAP.\nThank you.\n");
}
}
else {
System.out.println("Please start again.");
return;
}
}
}
我遇到的问题是我在 else 和 if 块中重复相同的 System.out.println() 主体。相反,我想做的是创建一个可以在每个块中调用的方法。
如果可能,我该怎么做?
【问题讨论】: