2015-11-13 49 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]+")");