2016-11-26 53 views
0

在我的程序中我有文件输入文件和控制台输出。在这里,我使用了数组中的文件I/O,但现在我想实现我的程序使用方法。 那么,如何在我的程序中使用方法? 谢谢。如何在数组中使用方法?

这里是我的代码:

public class score { 

    public static void main(String[] args) throws FileNotFoundException { 
     // TODO Auto-generated method stub 
     JFileChooser jfc = new JFileChooser("."); 
     int jfcUserOption = jfc.showOpenDialog(null); 
     if (jfcUserOption == JFileChooser.APPROVE_OPTION){ 
      File chosenFile = jfc.getSelectedFile(); 

      Scanner input = new Scanner(chosenFile); 


      int n = input.nextInt(); 
      double[] score = new double[n]; 
      int bestScore = 0; 


      for(int i = 0; i < n; i++) { 
       score[i] = input.nextDouble(); 
       if (bestScore < score[i]){ 
        bestScore = (int) score[i]; 
        } 
       } 

      char grade; 
      for (int i = 0; i < n; i++){ 
       if (score[i] >= bestScore - 15) 
        grade = 'A'; 
       else if (score[i] >= bestScore - 25) 
        grade = 'B'; 
       else if (score[i] >= bestScore - 35) 
        grade = 'C'; 
       else if (score[i] >= bestScore - 45) 
        grade = 'D'; 
       else 
        grade = 'F'; 

       System.out.println("Student " + (i + 1)+" score is " + score[i] +" and grade is " + grade); 

      } 


     } 

    } 

} 
+0

尝试[本教程](https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html) – ajb

回答

0

根据您要使用的方法是什么,你有很多的选项 - 这就是为什么方法是有用的。

一个好方法,认为它是打出来的步骤或行动纳入自己的方法,你的main()方法可以调用:

例如,在这里我们定义了一个新的方法findBestScore(),它我们使用要返回一个int值到它被称为在main()方法:

public class score { 

public static void main(String[] args) throws FileNotFoundException { 
    // TODO Auto-generated method stub 
    JFileChooser jfc = new JFileChooser("."); 
    int jfcUserOption = jfc.showOpenDialog(null); 
    if (jfcUserOption == JFileChooser.APPROVE_OPTION){ 
     File chosenFile = jfc.getSelectedFile(); 

     Scanner input = new Scanner(chosenFile); 


     int n = input.nextInt(); 
     double[] score = new double[n]; 
     int bestScore = findBestScore(); 

     char grade; 
     for (int i = 0; i < n; i++){ 
      if (score[i] >= bestScore - 15) 
       grade = 'A'; 
      else if (score[i] >= bestScore - 25) 
       grade = 'B'; 
      else if (score[i] >= bestScore - 35) 
       grade = 'C'; 
      else if (score[i] >= bestScore - 45) 
       grade = 'D'; 
      else 
       grade = 'F'; 

      System.out.println("Student " + (i + 1)+" score is " + score[i] +" and grade is " + grade); 

     } 


    } 

} 

public int findBestScore() { 

    int bestScore; 

    for(int i = 0; i < n; i++) { 

     score[i] = input.nextDouble(); 
      if (bestScore < score[i]){ 
       bestScore = (int) score[i]; 
      } 
    } 

    return bestScore; 
} 

}

这并不编译,但是,因为有一些失踪进口。