2014-10-05 67 views
-5

有人可以幫助我使用此代碼。java學生gpa文件和數組

這是文件

57363 Joy Ryder D D C P H H C D 

72992 Laura Norder H H H D D H H H 

71258 Eileen Over C F C D C C C P 

我想要的ID存儲在陣列中,5位數字和字符轉換爲數字和計算平均GPA其中H=7D=6C=6P=4F=0並將其存儲在第二個數組中。然後將這兩個文件從最大值到最小值進行排序,並將這些值寫入輸出文本文件。這是到目前爲止我的代碼

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class StudentGPA_17396934Demo { 

public static void main(String[] args) throws IOException { 

    Scanner kb = new Scanner(System.in); 

    String fileName; 
    char grade[] = new char[8]; 
    File myfile; 
    int num = 0; 

    do{ 
    System.out.println("Enter the name of the file: "); 
    fileName = kb.next(); 

    myfile = new File(fileName); 
    if (myfile.exists()) { 
     Scanner infile = new Scanner(myfile); 
     while (infile.hasNext()) { 

      int ID = infile.nextInt(); 
      String name = infile.next(); 
      String surname = infile.next(); 

      // it is converting the characters to numbers but not reading all characters 
      also how do I get average of this numbers and store in appropriate array 
      also how to store ID in array 
      for (int i = 0; i < grade.length; i++) { 
       grade[i] = infile.next().charAt(0); 

      if (grade[i] == 'H') 
      num = 7; 
      else if (grade[i] == 'D') 
      num = 6; 
      else if (grade[i] == 'C') 
      num = 5; 
      else if (grade[i] == 'P') 
      num = 4; 
      else if (grade[i] == 'F') 
      num = 0; 
      } 

      System.out.println(ID + "\t" +name + "\t" +surname + "\t" + num); 


     } 

    } 
    else{ 

     System.out.println("file not found..."); 
    } 
    }while(!myfile.exists()); 

} 

} 

和我的輸出是

Enter the name of the file: 
grades 

57363 Joy Ryder 6 

72992 Laura Norder 7 

71258 Eileen Over 4 
+1

什麼讓你煩惱?有什麼問題?如果這是你的作業,沒有人會爲你做:) – 2014-10-05 23:54:54

+0

我不知道如何將ID和成績存儲到數組中,並寫入文件 – user2423898 2014-10-05 23:56:26

+0

,這樣你就知道你的問題。第一個如何存儲在數組中,第二個如何寫入文件。所以試着谷歌他們,並學習他們。如果你被困在某個地方,讓我們知道。你必須學習如何研究 – 2014-10-05 23:57:16

回答

1

讓我們做一個例子作爲你的藍圖,以便能夠按照學習

如你所知,你需要一個array

讓我們看看array是在Java

數組是保存的 單一類型

值的固定數目的容器對象。它有一個長度,這意味着你可以保存一定數量的數據在它邊上

。對象的類型必須相同

enter image description here

讓我們來看看如何定義一個arrayJava

dataType[] arrayRefVar ; 

例如:int[] arryInt;

在Java中

創建數組
arrayRefVar = new dataType[arraySize]; 

例如arrayInt = new int[5];

如何將值分配給數組的每個索引

例如arrayInt[2] = 23;

如果要使用循環來填充你的數組,你可以做如下

for(int i =0; i < arrayInt.length ; i++){ 
     arrayInt[i] = i ; 
     System.out.print(" " + i); 
} 

輸出:0 1 2 3 4

注意:數組索引從零開始在Java中

+1

+1好的答案。 – JosEduSol 2014-10-06 01:57:49