public static void main(String[] args) throws IOException
{
// TODO code application logic here
File election = new File("voting_2008.txt");
Scanner sc = new Scanner(election);
String[] states = new String[51];
int[][]votes = new int[51][3];
for (int s=0; s < 51; s++)
{
states[s] = sc.nextLine();
}
for(int c=0; c < 3; c++)
{
for(int s=0; s < 51; s++)
{
votes[s][c] = sc.nextInt();
}
}
Formatter fmt = new Formatter();
fmt.format("%20s%12s%12s%12s%21s", "State", "Obama", "McCain", "Other", "Total by state");
System.out.println(fmt);
int TotalSum;
TotalSum = 0;
for (int s=0; s < 51; s++)
{
fmt = new Formatter();
fmt.format("%20s", states[s]);
System.out.print(fmt);
for(int c=0; c < 3; c++)
{
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
int sum =0;
for (int col=0; col < votes[s].length; col++)
{
sum = sum + votes[s][col];
}
TotalSum += sum;
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
System.out.println();
}
Formatter fmt2 = new Formatter();
fmt2.format("%20s%12s%12s%12s%21s", "Total", "", "", "", TotalSum);
System.out.print( fmt2 );
}
}
答案 0 :(得分:1)
一些简单的更改可以解决您的问题:
1&GT;将前两个for循环合并为:
for (int s=0; s < 2; s++){
states[s] = sc.next();
for(int c=0; c < 3; c++) {
votes[s][c] = sc.nextInt();
}
}
在TotalSum旁边定义一个新的colSum [],如下所示:
int TotalSum = 0;
int colSum[] = new int[]{0,0,0};
更新投票打印循环以执行列总和:
for(int c=0; c < 3; c++) {
colSum[c]+=votes[s][c]; // <-- new line to do the column sum
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
将最后一行的列总和打印为:
fmt2.format("%20s%12s%12s%12s%21s", "Total", colSum[0], colSum[1], colSum[2], TotalSum);
System.out.print( fmt2 );
希望这会有所帮助!!
答案 1 :(得分:0)
你的逻辑有点偏。
在第一次for循环之后:
for (int s=0; s < 51; s++)
{
states[s] = sc.nextLine();
}
您已经消耗了文件中的前50行,并且“states”数组中的每个元素都包含每行的文本。下次您尝试从扫描仪读取时,您将在第51行,因此您只需阅读文件底部的总计,如您最初所述。
我认为您想要做的是每个州(文件中的每一行)将数字列1,2和3加在一起?
以下是一些应该有用的示例代码:
File election = new File("voting_2008.txt");
Scanner scanner = new Scanner(election);
String[] states = new String[50]; // 50 united states
int[] votes = new int[50];
// only grab the first 50 lines, each line a different state
// assuming file layout is: stateName,count1,count2,count3
for ( int i = 0; i < 51; i++ ) {
states[i] = scanner.next();
// grab the next 3 numbers
int voteTotal = 0;
for ( int j = 0; j < 3; j++ ) {
voteTotal += scanner.nextInt();
}
votes[i] = voteTotal; // total votes for this state
}
// ... display results ..