【问题标题】:Create and call method that involves multiple System.out.println() and variables创建和调用涉及多个 System.out.println() 和变量的方法
【发布时间】: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() 主体。相反,我想做的是创建一个可以在每个块中调用的方法。

如果可能,我该怎么做?

【问题讨论】:

    标签: java string methods


    【解决方案1】:

    如果这是您的意思,那么您需要阅读基本 Java,我已在代码示例中添加了您的方法,请阅读此链接以了解有关方法的更多信息:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

    更多信息也请参见彼得的回答!

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

    【讨论】:

    • 澄清(有人发表评论然后删除) - 我相信操作员正在询问如何使用一种方法来保存重复代码,仅此而已。如果我错了,我很乐意更新我的答案:)
    • 这段代码有错误。请纠正他们。例如,在 PrintStuff() 中未定义 first_name。
    • @Zaphod42 - 谢谢。重新安装了我的机器,只有notepad++用于编码atm ... :)
    • 更新的代码,请取消投票 ;)... 或者随意投票! :-D
    • 谢谢。我现在还在学习 Java,还没有创建新方法。这回答了我的问题。
    【解决方案2】:

    不需要方法,只是一些DRY重构:

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

    【讨论】:

    • 虽然我已经选择了我接受的答案,但我必须承认这个更胜一筹。是什么 ”? : ;”叫什么?
    • @JohnJ.Kim 它被称为三元运算符:docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
    • @JohnJ.Kim 三元运算符只是执行 if/else 的一种更简洁的方式。在这种情况下,它与if (ch == 'y') cost = 5; else cost = 89;具有相同的效果。
    • @Bohemian 不过你的代码只有一件事。我的原始代码上的两个文本之间的区别在于“有资格获得费用减免”这一短语。还有一个“没有资格获得费用减免”。如果我将它设置为一个变量,它如何适合这里?
    • 您的问题在任何地方都没有“不符合条件”的文本 - y 和 n 的两个输出文本都是相同的。 ch == 'n' 的时候你想要“没有”吗?
    【解决方案3】:

    创建一个类似这样的方法:

    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();
    }
    

    那么您的 IF 语句将如下所示:

    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, ...);
    }
    

    【讨论】:

      【解决方案4】:

      您可以在打印重复的 System.out.println 的 main 之外创建另一个方法 而且这个方法可能包含这样的参数

       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");
      
      
      }
      

      在您的主目录中,您可以访问此方法或将其放入您的条件中,例如

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

      【讨论】:

      • first_name 未为 print() 定义。除了总计之外,您还需要其他参数。 Total 没有定义,所以这是一个语法错误。
      • 哦,是的,我忘了输入总计和其他参数的数据类型,但只要他了解流程..没关系
      【解决方案5】:

      您可以通过向该方法添加参数来完成此操作。一切
      if/else if 块之间打印的内容不完全相同
      和另一个else if 块,您为该方法创建一个参数。然后从
      调用相同方法但传递不同值的不同块
      用于参数。

      【讨论】:

        【解决方案6】:
        import static java.lang.System.out;
        

        将允许您简单地引用该代码,尽管通常被认为是一种不好的做法,并且仅适用于一次性程序。

        只需保存对 System.out 的引用即可为您节省该部分

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

        或者给自己写一个很好的速记方法

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

        您必须为 int、double 等编写重载,或者您可以使用字符串连接

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

        或者你的意思只是为了你的大块代码?那样的话……

        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");
            }
        

        现在打电话

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

        或其他。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-18
          • 2021-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-27
          • 2013-09-30
          • 1970-01-01
          相关资源
          最近更新 更多