gpt4 book ai didi

java - 如何在二维数组上正确使用格式化程序?

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:14 25 4
gpt4 key购买 nike

我必须将二维数组的行总和添加到右侧的列中。但是,当我运行代码时,它会添加每列中所有行的总和,直到到达末尾。像这样:/image/1QQZT.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();
}
}

}

最佳答案

   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); // You are not printing newline after each vote..
}

尝试使用: - System.out.println(fmt); 代替注释代码..

更新:-不要进行上述更改..不会工作。.确实进行以下更改。

问题在于..您正在打印您的总票数,51 * 51次..您将此循环放在另一个循环中,而该循环已经运行了51次..

所以,解决你的问题..从上面的代码中删除外循环,并保持如下:-

   //for(int row=0; row < votes.length; row++) // Remove this loop
//{ // Remove this

int sum =0;
for (int col=0; col < votes[s].length; col++)
{
sum = sum + votes[s][col];

}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
//} // Remove this also..

您从最外层​​循环获得的 s 值 ..

更新: - 如果您想要所有投票的总和..对于所有列..

int totalSum = 0;    // Declare a variable outside it..
for (int s=0; s < 51; s++) // This is the place where the loop started
{
fmt = new Formatter();
fmt.format("%20s", states[s]);
System.out.print(fmt);

// Other inner loops

int sum =0; // Your innerloop that calculates sum of each state..
for (int col=0; col < votes[s].length; col++)
{
sum = sum + votes[s][col];

}

totalSum += sum; // Add sum to `totalSum`
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);

// Continue with the outer loop
}

关于java - 如何在二维数组上正确使用格式化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com