我试图将此数据作为表格输出,但我无法使用我尝试过的任何方法制作功能性二维数组表。我正在尝试为 GradeList 和 devList 创建一个 7x2 矩阵。
我将预初始化数据和用户输入数据放入 3 个数组中。我正在尝试用其中两个制作一个表格(然后使用另一个作为标签)。 nameList 将是行的标签,“grade”和“deviation”将是列的标签(我还没有尝试设置)。
我已经注释掉了第一次尝试,它输出了正确的信息,但无法制作可读的表格。该程序可以编译,但每次我使用当前的矩阵尝试运行它时都会抛出错误。
抱歉,如果我忘记了任何有用的信息,感谢您的查看。
//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;
}
}
}
}
最佳答案
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;
}
}
}
这段代码工作正常...试试这个。
关于java - java中二维数组的输出表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22470623/