我试图将这些数据作为一个表输出,但我还没能用我尝试过的任何方法制作一个功能性的二维数组表。我试图为gradeList和devList创建一个7x2矩阵。
我将预先初始化和用户输入数据分成3个数组。我试图用其中两个制作一张桌子(然后用另一张作为标签)。 nameList将是行的标签,并且' grade'和'偏离'将是列的标签(我还没有试图设置它)。
我已经注释掉了第一次尝试,它输出了正确的信息,但无法制作可读的表格。程序编译,但是当我使用矩阵的当前尝试运行它时会抛出错误。
很抱歉,如果我忘记了任何有用的信息,感谢您的光临。
//This program determines the mean grade and deviation from that mean for a class of users.
import java.util.Scanner;
public class gradeArrays
{
static Scanner in = new Scanner(System.in);
static int avg;
//array declarations
static String[] nameList = {"Doc","Grumpy","Happy","Sleepy","Dopey","Sneezy","Bashful"};
static int[] gradeList = new int[7];
static int[] devList = new int[7];
//main method
public static void main(String[] args)
{
System.out.println("This program will calculate the mean, and the deviation from that mean, for 7 students.");
getGrades(gradeList);
meanCalc(gradeList);
devCalc(gradeList, avg);
tableOut(gradeList, devList, avg);
}
//input scores from user, method 1
public static int[] getGrades(int[] gradeList)
{
for (int i=0; i < nameList.length; i++)
{
System.out.println("What is the grade for " + nameList[i] + "?");
gradeList[i]= in.nextInt();
}
return gradeList;
}
//calculate average, method 2
public static int meanCalc(int[] gradeList)
{
int sum = 0;
for (int i = 0; i < nameList.length; i++)
{
sum = sum + gradeList[i];
}
if (gradeList.length !=0)
{
avg = sum / gradeList.length;
}
else
{
avg = 0;
}
return avg;
}
//calculate deviation, method 3
public static int[] devCalc(int[] gradeList, int avg)
{
for (int i = 0; i < nameList.length; i++)
{
devList[i] = gradeList[i] - avg;
}
return devList;
}
//output, method 4
public static void tableOut(int[] gradeList, int[] devList, int avg)
{
/*
System.out.println(" Student Grade Deviation");
for (int i = 0; i < nameList.length; i++)
{
System.out.print(" " + nameList[i] + " ");
System.out.print(" " + gradeList[i] + " ");
System.out.printf(" " + "%7d", devList[i]);
System.out.println();
}
System.out.println("The average grade was " + avg + ".");
*/
int[][] outTable = new int[7][2];
for (int row = 0; row < nameList.length; row++)
{
for (int col = 0; col < 3; col++)
{
outTable[row][col] = 21;
}
}
}
}
答案 0 :(得分:1)
public static void tableOut(int[] gradeList, int[] devList, int avg)
{
System.out.println("\tStudent\tGrade\tDeviation");
for (int i = 0; i < nameList.length; i++)
{
System.out.print("\t" + nameList[i] + "\t");
System.out.print("\t" + gradeList[i] + "\t");
System.out.printf("\t" + "%7d", devList[i]);
System.out.println();
}
System.out.println("The average grade was " + avg + ".");
int[][] outTable = new int[7][2];
for (int row = 0; row < nameList.length; row++)
{
for (int col = 0; col <2; col++)
{
outTable[row][col] = 21;
}
}
}
此代码正常运行...试试这个。