2015-11-13 73 views
-1

如果有人願意給我一個這個程序的手,它將不勝感激,它接受多個學生的姓名和成績使用掃描儀,然後將它們放入2個數組,學生和分數。然後它會打印出如下...Java掃描器輸入到int和字符串數組

最大。等級= 98(勞倫)

最小。等級= 50(Joe)

平均等級= 83.9

/* Chris Brocato 
* 10-27-15 
* This program will read the students names and scores using a Scanner and use two arrays to 
* show the grade and name of the highest and lowest scoring student as well as the average grade.*/ 

import java.util.*; 

public class StudentCenter { 

    public static void main(String[] args) { 
     Scanner console = new Scanner(System.in); 
     System.out.print("Please enter the number of students: "); 
     int students = console.nextInt(); 
     String[] name = new String[students]; 
     int[] scores = new int[students]; 

     int min = 0; int max = 0; int sum = 0; 
     for (int i = 0; i < name.length; i++) { 
      System.out.print("Please enter student's name: "); 
      name[i] = console.next(); 
      System.out.print("Now enter their score: "); 
      scores[i] = console.nextInt(); 
      if (i == 0) { 
       min = students; 
       max = students; 
      }else { 
       if (students < min) min = students; 
       if (students > max) max = students; 
      }sum += students; 
     } 
     System.out.println("Min. Grade = " + min + name); 
     System.out.println("Max. Grade = " + max + name); 
     System.out.println("Average Grade = " + sum); 
     double avg = (double) sum/(double) students; 
     System.out.println("Avg = " + avg); 
     console.close(); 
     } 

    } 
+1

這不是問題。你有什麼特別的問題? –

+0

對不起,我沒有得到正確的輸出,最小和最大都給出了相同的數字,我認爲它只是最後輸入的數字,但我不明白爲什麼。 –

回答

1

你設置minmaxsumstudents的價值,這是學生而不是自己得分的數量。您應該將它們設置爲scores[i]

if (i == 0) { 
    min = scores[i]; 
    max = scores[i]; 
}else { 
    if (students < min) min = scores[i]; 
    if (students > max) max = scores[i]; 
} 
sum += scores[i]; 

我也想存儲的最小和最大的分數指數,這樣就可以在以後引用他們的名字。

min = scores[i]; 
minIndex = i; 
... 
System.out.println("Min. Grade = " + min + name[minIndex]); 
+0

好的,謝謝,您解決了我的問題,但是當我完成min和maxIndex時,會將第一個名稱輸入到輸出中 –

+0

您必須更新最小/最大索引值,無論您將最小/最大得分值更新爲保持同步。 –

0

我會使用常數的最小值和最大值。

int max = Integer.MIN_VALUE; 
int min = Integer.MAX_VALUE; 
int maxValue = 0; 
int minValue = 0; 
String minName; 
String maxName; 

//then use them for comparison in the loop 

if(scores[i] < min) 
{ 
minValue = scores[i]; 
minName = name[i]; 
} 

if(scores[i] > max) 
{ 
maxValue = scores[i]; 
maxName = name[i]; 
} 

將在您的最大/最小值存儲與相關聯的名稱。

0

您正在比較最小值和最大值的錯誤值。學生是你沒有成績的學生人數。同樣當打印臨時名稱時,您正在打印整個數組,而不僅僅是一個特定的值。所以我的建議是,你創建的兩個變量是這樣的:

int minInd = 0; int maxInd = 0;

然後改變你的,如果是這樣的:

if (i == 0) { min = scores[i]; max = scores[i]; } else { if (scores[i] < min) { min = scores[i]; minInd = i; } if (scores[i] > max) { max = scores[i]; maxInd = i; } } sum += scores[i];

並打印結果是這樣的:

System.out.println("Min. Grade = " + min + " ("+ name[minInd]+")"); System.out.println("Max. Grade = " + max + " ("+name[maxInd]+")");