UnP*_*uac 0 java arrays multidimensional-array
我想添加每个州的投票总数和这个二维数组的每个候选人的总和.
这些是要求:
修改程序,以便显示每个候选人的总投票数(即,添加最后一行,显示所有三列投票的总投票数)
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);
}
int sum =0;
for(int row=0; row < votes.length; row++)
{
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
}
fmt = new Formatter();
fmt.format("%21d", Totalbystate) ;
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)这个问题与求和无关,而且与格式化有关.只是这段代码将演示同样的问题:
int[] values = new int[10];
new Formatter().format("%21d", values);
Run Code Online (Sandbox Code Playgroud)
目前还不清楚你对此的期望是什么,但我怀疑你实际上想做的事情如下:
// Please change your variable names to follow Java conventions
fmt = new Formatter(System.out);
for (int value : Totalbystate) {
fmt.format("%21d", value);
}
Run Code Online (Sandbox Code Playgroud)
或者,指定单个格式字符串,例如"%21d%21d%21d%21d%21d"(etc)并传入Integer[]而不是传入int[].
另外,你应该修复程序的缩进 - 这在目前是不必要的混乱.