2009-08-17 7 views
1

이것은 CSE 201에서 작업하는 실험실입니다.이 프로그램은 학생과 학생의 점수에 대한 정보를 파일에서 읽고 모든 학생의 이름을 출력합니다. 점수 및 총점 수, 그리고 수업의 평균 점수, 총점이 가장 높고 가장 낮은 학생의 이름 및 총점.초급 Java (컴파일하기 위해 클래스 지정 받기)

정확한 할당은 here으로 볼 수 있습니다.

특히 "students"변수를 사용하여 컴파일하는 데 약간의 문제가 있습니다. 도움이 될 것입니다.

/* 
* The program will read information about students and their 
* scores from a file, and output the name of each student with 
* all his/her scores and the total score, plus the average score 
* of the class, and the name and total score of the students with 
* the highest and lowest total score. 
*/ 

import java.util.Scanner; 

public class Lab7 
{ 
     public static void main(String[] args) 
     { 
       // Input file name 
       Scanner in = new Scanner(System.in); 
       String filename = getFileName(in); 

       // Input number of students 
       int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename)); 

       // Input all students records and create Student array and 
       // integer array for total scores 
       int[] totalScores = new int[students.length]; 
       for(int i = 0; i < students.length; i++){ 
         for(int j = 1; j < 4; j++){ 
           totalScores[i] += students[i].getScore(j); 
         } 
       } 

       // Compute total scores and find students with lowest and 
     // highest total score 
       int maxIndex = 0, minIndex = 0; 
       for(int i = 0; i < students.length; i++){ 
         if(totalScores[i] > totalScores[maxIndex]){ 
           maxIndex = i; 
         }else if(totalScores[i] < totalScores[minIndex]){ 
           minIndex = i; 
         } 
       } 

       // Compute average total score 
       int average = 0; 
       for(int i = 0; i < totalScores.length; i++){ 
         average += totalScores[i]; 
       } 
       average /= students.length; 

       // Output results 
       outputResults(students, totalScores, maxIndex, minIndex, average); 

     } 

     // Given a Scanner in, this method prompts the user to enter 
     // a file name, inputs it, and returns it. 
     private static String getFileName(Scanner in) 
     { 
       System.out.print("Enter input file name: "); 
       return in.nextLine(); 
     } 

     // Given the number of students records n to input, this 
     // method creates an array of Student of the appropriate size, 
     // reads n student records using the FileIOHelper, and stores 
     // them in the array, and finally returns the Student array. 
     private static Student[] getStudents(int n) 
     { 
       Student[] student = new Student[n]; 
       for(int i = 0; i < student.length; i++){ 
         student[i] = FileIOHelper.getNextStudent(); 

       } 
       return student; 
     } 

     // Given an array of Student records, an array with the total scores, 
     // the indices in the arrays of the students with the highest and 
     // lowest total scores, and the average total score for the class, 
     // this method outputs a table of all the students appropriately 
     // formatted, plus the total number of students, the average score 
     // of the class, and the name and total score of the students with 
     // the highest and lowest total score. 
     private static void outputResults(
         Student[] students, int[] totalScores, 
         int maxIndex, int minIndex, int average 
     ) 
     { 
       System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal"); 
       System.out.println("--------------------------------------------------------"); 
       for(int i = 0; i < students.length; i++){ 
         outputStudent(students[i], totalScores[i], average); 
         System.out.println(); 
       } 
       System.out.println("--------------------------------------------------------"); 
       outputNumberOfStudents(students.length); 
       outputAverage(average); 
       outputMaxStudent(students[maxIndex], totalScores[maxIndex]); 
       outputMinStudent(students[minIndex], totalScores[minIndex]); 
       System.out.println("--------------------------------------------------------"); 
     } 

     // Given a Student record, the total score for the student, 
     // and the average total score for all the students, this method 
     // outputs one line in the result table appropriately formatted. 
     private static void outputStudent(Student s, int total, int avg) 
     { 
       System.out.print(s.getName() + "\t"); 
       for(int i = 1; i < 4; i++){ 
         System.out.print(s.getScore(i) + "\t"); 
       } 
       System.out.print(total + "\t"); 
       if(total < avg){ 
         System.out.print("-"); 
       }else if(total > avg){ 
         System.out.print("+"); 
       }else{ 
         System.out.print("="); 
       } 
     } 

     // Given the number of students, this method outputs a message 
     // stating what the total number of students in the class is. 
     private static void outputNumberOfStudents(int n) 
     { 
       System.out.println("The total number of students in this class is: \t" + n); 
     } 

     // Given the average total score of all students, this method 
     // outputs a message stating what the average total score of 
     // the class is. 
     private static void outputAverage(int average) 
     { 
       System.out.println("The average total score of the class is: \t" + average); 
     } 

     // Given the Student with highest total score and the student's 
     // total score, this method outputs a message stating the name 
     // of the student and the highest score. 
     private static void outputMaxStudent(
         Student student, 
         int score 
     ) 
     { 
       System.out.println(student.getName() + " got the maximum total score of: \t" + score); 
     } 

     // Given the Student with lowest total score and the student's 
     // total score, this method outputs a message stating the name 
     // of the student and the lowest score. 
     private static void outputMinStudent(
         Student student, 
         int score 
     ) 
     { 
       System.out.println(student.getName() + " got the minimum total score of: \t" + score); 
     } 
} 
+3

학생 신고는하지 않습니까? – Nelson

+0

작성자의 출력을 인쇄하면 유용 할 수 있습니다. – OscarRyz

+0

SO에 대한 절반 이상의 사람들이 동의하지 않지만 작성한 전체 시간을 컴파일해야합니다.IDE (예 : Eclipse 또는 Netbeans)는 구문 오류가 발생한 곳을 알려줍니다. 허용 된 시간이 있다면 몇 가지 도구를 사용하십시오. 나는 텍스트 편집기를 사용하여 자바를 배웠고 엄청난 시간 낭비였다. –

답변

3

배열의 크기는 왼쪽면에 지정할 수 없습니다.

학생 배열 선언은 다음과 같아야합니다

int noOfStudents = FileIOHelper.getNumberOfStudents(filename); 
//create an array of students of the given length 
Student[] students = new Student[noOfStudents]; 
1

이 부분은 문제가 될 수 같습니다

// Input number of students 
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename)); 
당신은 아마 먼저 변수를 사용 후, 학생들의 수를 싶어

getStudents를 호출합니다. 또한 배열을 학생이라고 부르기를 원하면 대괄호 안에 있으면 안됩니다.

Student[] students = ..... 
1

당신은 문제가있는 것은 main() 상단의 첫 번째 라인은 라인 :

int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename)); 
난 항상 컴파일러와 같은 사고 방식과 문제가있는 라인을 통해 읽어 보시기 바랍니다

: 그것을 위에서 아래로, 왼쪽에서 오른쪽으로 말한 것을 제외하고는 아무것도 모릅니다.

그럼 처음부터 시작하자 :

int 

나는 int가 무엇인지! 당신은 하나를 선언하고 싶다! 굉장해! ...에 이동

Student 

지옥은 Student 무엇입니까? 나는 그것이 무엇인지 말해 줄 코드에서 어디서나을 볼 수 없다! 클래스 이름은 항상 Java로 대문자로되어 있기 때문에 인간의 것으로 추측 할 수 있지만 컴파일러가 확신 할 수 없도록 선언되지 않았습니다. 아마도 클래스 (Lab7 대신)라는 이름으로되어 있습니까?

더 중요한 것은 클래스 인 경우 행에 두 데이터 유형, 즉 intStudent을 방금 명명했습니다. 어떤 유형을 사용 하시겠습니까? 아마도 Student의 목록을 원한다면 int은 전혀 관련이 없습니다. 학생의 을 원하면 int이 적합합니다.

에 이동 :

students 

은 도대체가 students 무엇입니까?다시는 을 보지 못합니다. 무엇이 있는지 알려주는 코드에서!

잠시 후 돌아 가자. 너 여기서 뭘 하려구? 파일에있는 모든 학생의 배열을 얻으려고합니다. getStudents() 기능이이를 실현할 수 있습니다. (버그가있을 수 있지만 지금은 문제가 아닙니다. 그냥 여기에서 부르기 만하므로 작동하는 것으로 가정합니다.)

하지만 배열을 만드는 데 얼마나 큰지 알고 있어야합니다. 아직 읽지 않았 니? 편리하게, 당신은 알 필요가 없습니다! 당신은 간단하게 작성할 수 있습니다

Student[] 

당신입니다 getStudents()에서 아래로 배열을 인스턴스화하고이 올바르게 그것에게 크기를 부여했습니다. 여기 main()에 간단히 선언하고 있으므로 크기가 필요 없습니다.

좋아, 그냥 쓸 수는 :

Student[] = getStudents(FileIOHelper.getNumberOfStudents(filename)); 

아니, '당신의 변수가 이름을 가지고 있지 않은 원인이된다. 어떻게 이런 일에 대해 :

Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename)); 

나는 "떨어진"그건 당신이 의도,하지만 당신이 얻을 수있는 것이 중요하다 길을 따라 어딘가에 붙어있어 이후 의심 정신적 컴파일러가 보는 것을 통해 걷고있다 그것을하는 유용한 방법.

+0

강력하게 형식화 된 언어에서만 유효합니다. –

+0

음 ... "컴파일러처럼 생각하세요"라는 라인을 따라 : * what * heck *은 "int Student []"입니까 ?? –

+0

올바른 언어를 사용하는 것이 도움이 될 것 같습니다. 그에 따라 편집 됨. – VoteyDisciple

5

우선 : 컴파일러 오류에 실제로주의를 기울이는 것이 항상 유용합니다. Java의 컴파일러 오류는 대개는 매우 명확하고 유용합니다. 오류를 이해하면 무엇이 잘못되었는지 정확하게 알려줍니다.

: 그리고 일반적으로, 그것은 당신이 오류의 실제 텍스트를 포함 할 경우 오히려이 처음 분명히 잘못된 라인

"나는 문제가 컴파일러 점점이"말보다 당신을 도와 SO 여기에 사람들이 훨씬 쉽게

int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename)); 

자바에서 변수 선언 (약간 간략화) 구성

  • 가변
  • 이름 유형
  • O
  • ptionally 위의 줄에 초기 값

의 할당, 당신은 유형 int로 시작하지만, 다음 부분 Student[students]는 이해되지 않는다 - 그것은 확실히 이름, 배열 인스턴스처럼 보인다. 당신이 아마 의미 것은 :

Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename)); 

즉 유형이 Student[] (학생 객체의 배열), 이름, '학생'이다와는 getStudents() 메서드의 반환 값을 할당합니다. int은 여기에 포함되어 있지 않으므로 여기에 배열의 크기를 지정하지 않아도됩니다 (getStudents() 메서드 내에서 만들어지기 때문에).

+0

나는 같은 대답을 입력하는 중반이었습니다 –

+0

"서쪽에서 가장 빠른 총"문제라고도합니다 : –

+0

분명히 분명하지 않았습니다. ;-) –

관련 문제