我有一个程序可以生成一个数字列表并计算所有数字并将它们分成三个不同的列表。一个是所有数字,另外两个是偶数和奇数,然后打印偶数和奇数数组。
或者当我尝试打印出两个列表的某些原因时,它只打印ArrayList中的前几个数字,给出了我没有错误信息。
我的代码:
import java.util.Random;
import java.util.ArrayList;
public class Projects {
public static void main(String [] args) {
Random Generate = new Random ();
ArrayList<Double> List = new ArrayList<>();
ArrayList<Double> Even = new ArrayList<>();
ArrayList<Double> Odd = new ArrayList<>();
double number;
double total = 0;
double totalEven = 0;
double totalOdd = 0;
double averageWhole;
double averageEven;
double averageOdd;
System.out.println("Generating Numbers:");
for (int Repeater = 0; Repeater < 10; Repeater++) {
number = Generate.nextInt(100);
List.add(number);
}
System.out.println("Loaded... " + "Putting Numbers Into List");
System.out.println();
for(int Insert = 0; Insert < 3; Insert++) {
System.out.println("Adding To List...");
}
System.out.println("List Completed!");
System.out.println();
System.out.println();
for (int x = 0; x < List.size(); x++) {
total += List.get(x);
//Complicated Code --- really big for loop try to simplify later.
if (List.get(x) % 2 == 0) {
Even.add(List.get(x));
}
else {
Odd.add(List.get(x));
}
}
System.out.println("Your Total Is: " + total);
System.out.println();
System.out.println();
System.out.println("Even Numbers:" + "\t" + "Odd Numbers");
for (int Output = 0; Output < Even.size() && Output < Odd.size(); Output++)
{
System.out.println(Even.get(Output) + "\t" + "\t" + Odd.get(Output));
}
averageWhole = total / List.size();
System.out.println("Average of All Numbers: " + "Average of All Even Numbers: "+ "Average of all Odd Numbers: " );
for (int averageE = 0; averageE < Even.size(); averageE++) {
totalEven = totalEven + Even.get(averageE);
}
averageEven = totalEven / Even.size();
for (int averageO = 0; averageO < Odd.size(); averageO++) {
totalOdd = totalOdd + Odd.get(averageO);
}
averageOdd = totalOdd / Odd.size();
System.out.print(averageWhole + "\t" + "\t" + "\t" + " " + averageEven + "\t" + "\t" + "\t" + "\t" + " " + averageOdd);
System.out.println();
System.out.println();
System.out.println("Command Complete...");
很抱歉它被压缩了 - 学习java - 2/3周 - 谢谢!
答案 0 :(得分:0)
当您打印奇数和偶数时,将在完成较短列表时满足循环中的条件,因此打印在打印所有数字之前停止。您将打印分成两个独立的循环。
for (int i = 0; i < Even.size(); i++) {
System.out.println(Even.get(i));
}
for (int i = 0; i < Odd.size(); i++) {
System.out.println(Odd.get(i));
}
作为旁注,Java中的变量应该以小写开头。 Even
,Odd
,Output
等应为even
,odd
,output
。
答案 1 :(得分:0)
Guy的代码的另一种替代方式,保持相同的格式:
for (int Output = 0; Output < Even.size() || Output < Odd.size(); Output++) {
String even = "-";
if(Output < Even.size()){
even = Even.get(Output).toString();
}//end of if
String odd = "-";
if(Output < Odd.size()){
odd = Odd.get(Output).toString();
}
System.out.println(even + "\t" + "\t" + odd);
}