1

I'm working on a little Java program that outputs a receipt to email students who registered for an AP exam at my school. The code looks like this.

// 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;
        }
    }
}

The problem I have with this is that I am repeating the same System.out.println() body in the else and if blocks. Instead, what I would like to do is to perhaps create a method that could be called in each block.

If possible, how can I accomplish this?

6 Answers 6

3

If this is what you mean, then you need to read up on basic Java, I've added your method in the code sample, please read this link to understand more about methods: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

See Peter's answer for more information too!

// Create email text body for student who registered for an AP exam.

import java.util.Scanner;

class EmailText {

    public static void main(String args[]) {

        int numTests, cost;
        String email, first_name;
        char ch;

        Scanner input = new Scanner(System.in);

        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;
                PrintStuff(numTests, cost, email, first_name, "qualified for a fee waiver, ");
            }
            else if(ch == 'n') {
                cost = 89;
                PrintStuff(numTests, cost, email, first_name, "did not qualify for a fee waiver, ");
            } else {
                System.out.println("Please start again.");
            }
        }
    }

    public static void PrintStuff(int numTests, int cost, String email, String first_name, String fw_status) {
        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 " + fw_status +
                "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 Student Store ASAP.\nThank you.\n");
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

To clarify (someone posted a comment then deleted) - I believe the op is asking about how to use a method to save duplicate code, nothing more than that. If I'm wrong, I'd be happy to update my answer :)
You have bugs in this code. Please correct them. first_name is undefined in PrintStuff(), for instance.
@Zaphod42 - Thanks for that. Reinstalled my machine, only have notepad++ for coding atm... :)
Updated code, please un-down vote ;)... Or feel free to up-vote! :-D
Thanks. I'm still learning Java right now, and I haven't got to creating new methods yet. This answers my question.
|
2

No need for a method, just some DRY refactoring:

if(ch == 'y' || ch == 'n') {
    cost = ch == 'y' ? 5 : 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.\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 {
    System.out.println("Please start again.");
    return;
}

5 Comments

Although I have already chosen my accepted answer, I must admit that this one is superior. What is the "? : ;" thing called?
@JohnJ.Kim It's known as a ternary operator: docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
@JohnJ.Kim The ternary operator is just a more concise way of doing an if/else. In this case, it has the same effect as if (ch == 'y') cost = 5; else cost = 89;.
@Bohemian There is just one thing with your code there though. The difference between the two texts on my original code is in the phrase "qualified for a fee waiver". There is also a "did not qualify for a fee waiver". If I were to set this into a variable, how would it fit in here?
Your question doesn't have the text "did not qualify" anywhere in it - both output texts are the same for y and n. Do you want "did not" for when ch == 'n'?
0

Create a method something like this:

private String createOutput(int cost, String email, String first_name...)
{
    StringBuffer outputBuffer = new StringBuffer();
    outputBuffer.append("** Copy/Paste this Draft **\n");
    outputBuffer.append("To: " + email + "\n");
    outputBuffer.append("Subject: 2014 AP Test Receipt for " + first_name + "\n");
    outputBuffer.append("\n");
    ...

    return outputBuffer.toString();
}

Then your IF statement will look like this:

if(ch == 'y') {
    cost = 5;
    int total = numTests * cost;
    System.out.println(createOutput(cost, email, first_name, ...);
}
else if (ch == 'n') {
    cost = 89;
    int total = numTests * cost;
    System.out.println(createOutput(cost, email, first_name, ...);
}

Comments

0

You can create another method outside the main that prints your repeated System.out.println and this method may contain parameters like this

 public void print(total){
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");


}

and in your main you can access this method or put it inside your conditions like

 if(ch == 'y') {
               cost = 5;
                int total = numTests * cost;
               print(total);

}

2 Comments

first_name is undefined for print(). You will need additional parameters other than just total. Total isn't defined, so that's a syntax error.
oh yeah i forgot to put the data type of total and other parameters but as long as he understand the flow..its okay
0

You accomplish this by adding parameters to this method. Everything
which is not to be printed exactly the same between one if/else if block
and another else if block, you make a parameter of the method. Then from
the different blocks you call the same method but you pass different values
for the parameters.

Comments

-2
import static java.lang.System.out;

Will allow you to simply refer to that code, although is generally considered a bad practice and is only for one-off programs.

Simply saving a reference to System.out will save you that part

PrintStream out = System.out;
out.println( "hello" );

Alternatively write yourself a nice shorthand method

public static void print(String s){
     System.out.println(s);
     }

You'll have to write overloads for int, double, etc. or alternatively you can use string concatenation

int x = 10;
print(x + "");

Or did you mean just for your big block of code there? In that case...

public void printBlock(String email, String first_name, int numTests, int cost, int total){
                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");
    }

Now just call

if(thing){
printBlock("email","firstname",1,10,10);
}
else{
printBlock("email","othername",2,20,40);
}

Or whatever.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.