【发布时间】:2012-10-09 17:11:01
【问题描述】:
我必须将一列中二维数组的行之和添加到右侧。但是,当我运行代码时,它会添加每列中所有行的总和,直到它到达末尾。像这样:http://i.imgur.com/7CCPu.png 总和是正确的,但假设每行只有一次。
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][4];
int[] Totalbystate = new int[votes.length];
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);
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);
}
for(int row=0; row < votes.length; row++)
{
int sum =0;
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
}
System.out.println();
}
}
}
【问题讨论】:
-
你又来了同样的问题??你本可以只在那里要求澄清。事实上你在那里接受了答案。
-
抱歉,一位用户告诉我这是一个不同的问题
-
@user1663414.. 查看我的更新以解决您的代码中的问题.. 我建议了一个适合您的更改.. :)
标签: java multidimensional-array formatter