【问题标题】:Declaring Methods and Returning Values声明方法和返回值
【发布时间】:2016-10-23 00:06:32
【问题描述】:

我有一个完整的程序,但不确定如何在主程序中调用该方法?我的返回值需要是:

(word + " appears " + count + " times " );

("The average score for reviews containing the word horrible is " + average);

所有代码都需要保留在 methodOne 中。我只需要知道,如何调用该方法并返回正确的值?

注意:我非常是 Java 新手,所以请不要使用复杂的想法

当前代码: 导入 java.util.Scanner; 导入java.io.File; 导入 java.io.FileNotFoundException;

public class ReactionAnalysis {
  public static void main (String [] args)
  {
    System.out.println("Call Method One:");

  }


  public static String methodOne() throws FileNotFoundException
  {

Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = keyboardInput.next();

File inputFile = new File("movieReviews.txt");
Scanner movieReview = new Scanner(inputFile);

String reviewText;
int reviewScore;
int count = 0;
double total = 0;

while (movieReview.hasNext())
{
  reviewScore = movieReview.nextInt();
  reviewText = movieReview.nextLine();

  if (reviewText.contains(word))
  {
    count++;
    total = total + reviewScore;
  }

}
    String str = (word + " appears " + count + " times " );
    double average = (total / count );
    String str2 = ("The average score for reviews containing the word horrible is " + average);
    return str + str2;
}
}

【问题讨论】:

    标签: java


    【解决方案1】:

    实际上并没有用于将代码放入方法的模板...您只需让方法返回您想要的内容,并尽可能高效地做到这一点。

    您可以返回多个值的一种方法是返回一个数组(或者您可以使用ArrayList,但在这种情况下这将是矫枉过正。)您可以在方法内进行所有计算,当一切都说了并完成返回包含您希望它们的Strings 的数组。例如:

    import java.util.Scanner;
    import java.io.File;
    import java.io.FileNotFoundException;
    public class methodOne {
        public static void main(String[] args) {
            Scanner keyboardInput = new Scanner(System.in);
            System.out.println("Enter a word: ");
            String word = keyboardInput.next();
    
            File inputFile = new File("movieReviews.txt");
    
            String[] data = wordCount(word, inputFile);
    
            for(int i =0; i < data.length; i++) {
                System.out.println(data[i]);
            }
        }
    
        public static String[] wordCount(String word, File inputFile) {
            String[] results = new String[2];
            Scanner movieReview = null;
            try {
                movieReview = new Scanner(inputFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
    
            String reviewText;
            int reviewScore;
            int count = 0;
            double total = 0;
    
            while (movieReview.hasNext()) {
                reviewScore = movieReview.nextInt();
                reviewText = movieReview.nextLine();
                if (reviewText.contains(word)) {
                    count++;
                    total = total + reviewScore;
                }
            }
    
            double average = total/count;
            results[0] = word + " appears " + count + " times";
            results[1] = "The average score for reviews containing the word" + word + " is " + average;
            return results;
        }
    }
    

    如果您有任何问题,请随时告诉我!

    【讨论】:

    • results = new String[2]在哪里?
    • 谢谢你这帮助我弄清楚如何命名方法!但是现在我需要在不移动任何代码的情况下将 methodOne 调用到 main 中。
    • 在我上面贴的代码中,该方法已经在main方法中调用了:String[] data = wordCount(word, inputFile);。这使得String[] data 成为方法内部的String[] results = new String[2]
    【解决方案2】:

    将值传递给方法相当简单。例如:

        public class NewClass {
        public static void main(String[] args) {
            // passing two literal strings into the method
            // and then invoking it
            System.out.println(strCombo("Hello, ", "world!"));             
        }
    
        // if you are going to call a method in main, it must be static
        public static String strCombo(String str, String str2) {        
            return str + str2;
        }
    } 
    

    这适用于任何数据类型,如果它不返回任何内容,您只需将其设置为正确的或 VOID。

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      有很多方法可以改进此代码,但为了使其简单而有用,我建议您:

      • 创建一个方法来封装你的整个逻辑:readReviews();
      • 让此方法返回一个包含 2 条预期行的数组;
      • 从你的 main 中调用方法:String[] result = program.readReviews();(我建议使用 Result 对象,但不适合 OP);
      • 遍历结果以打印每一行。

      完整代码:

      public class methodOne {
          public static void main(String[] args) throws FileNotFoundException {
              methodOne methodOne = new methodOne();
              String[] result = methodOne.readReviews();
              
              for(String res: result){
                  System.out.println(res);
              }
      
          }
          
          public String[] readReviews() throws FileNotFoundException{
              Scanner keyboardInput = new Scanner(System.in);
              System.out.println("Enter a word: ");
              String word = keyboardInput.next();
      
              File inputFile = new File("movieReviews.txt");
              Scanner movieReview = new Scanner(inputFile);
      
              String reviewText;
              int reviewScore;
              int count = 0;
              double total = 0;
      
              while (movieReview.hasNext()) {
                  reviewScore = movieReview.nextInt();
                  reviewText = movieReview.nextLine();
      
                  if (reviewText.contains(word)) {
                      count++;
                      total = total + reviewScore;
                  }
              }
              
              double average = (total / count);
              return new String[]{ 
                      word + " appears " + count + " times ", 
                      "The average score for reviews containing the word horrible is " + average};
          }
      }
      

      【讨论】:

      • 我正在寻找一些只有一个类的代码!只想在我的main中调用我methodOne中的代码!
      • Result 类嵌入在 methodOne 中可以吗?
      • 对于这个项目,我只应该有一个类,反应分析