我想从输入数组列表中打印偶数和奇数。
输入:1 2 3 4
预期产量
偶数是:2 4
奇数是:1 3
但是我得到的输出是
Odd number is [1]
Even number is [2]
Odd number is [1, 3]
Even number is [2, 4]
我认为for循环可能放错了位置吗?
import java.util.ArrayList;
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> odd = new ArrayList<Integer>();
int[]number=new int[10];
Scanner read = new Scanner (System.in);
System.out.print("Enter number :" );
for(int i=0;i<number.length;i++){
number[i]=read.nextInt();
if(number[i]%2==0){
even.add(number[i]);
System.out.println("Even number is " + even);
}
else{
odd.add(number[i]);
System.out.println("Odd number is " + odd);
}
}
}
}
答案 0 :(得分:2)
程序正常运行,但是您的println
语句应放在for
循环之后而不是循环内部。输出显示它正在打印奇数和偶数列表,因为它们是生成的,而不是在处理完整个输入集之后。
...
for(int i=0;i<number.length;i++){
number[i]=read.nextInt();
if(number[i]%2==0)
even.add(number[i]);
else
odd.add(number[i]);
}
System.out.println("Even number is " + even);
System.out.println("Odd number is " + odd);
...
答案 1 :(得分:1)
public static void main(String[] args) {
ArrayList<Integer> even = new ArrayList<Integer>();
ArrayList<Integer> odd = new ArrayList<Integer>();
int[] number = new int[10];
Scanner read = new Scanner(System.in);
System.out.print("Enter number :");
for (int i = 0; i < number.length; i++) {
number[i] = read.nextInt();
if (number[i] % 2 == 0) {
even.add(number[i]);
} else {
odd.add(number[i]);
}
}
System.out.println("Even number is :");
for (Integer e : even) {
System.out.print(e + " ");
}
System.out.println("\nOdd number is :");
for (Integer o : odd) {
System.out.print(o + " ");
}
}
您正在for循环中进行打印,以读取用户输入。在进行上述输入后,打印数据。
还请注意使用 println 和 print 方法格式化输出的方式。