这个程序正在努力分离负数,奇数和偶数整数。编译时,它会向用户询问2个数字而不是1个数字,然后中断。如何通过要求2个数字来修复它。
import java.util.Scanner;
import java.util.Arrays;
public class Integer{
public static void main(String [] args){
Scanner reader = new Scanner (System.in);
double number;
int count = 0;
double [] evenList = new double[count];
double [] oddList = new double[count];
double [] negativeList = new double[count];
for (int i = 0; i < 10; i++){
System.out.println("Please enter an integer: ");
number = reader.nextDouble();
count++;
if (number < 0) {
negativeList[i] = reader.nextDouble();
}
if (number % 2 == 0) {
evenList[i] = reader.nextDouble();
} else {
oddList[i] = reader.nextDouble();
}
}
System.out.println("Negatives: " + Arrays.toString(negativeList));
System.out.println("Odds: " + Arrays.toString(oddList));
System.out.println("Evens: " + Arrays.toString(evenList));
}
}
答案 0 :(得分:1)
您正在if
块内的扫描仪再次读取值。请改用number
if (number < 0) {
negativeList[i] = number;
}
if (number % 2 == 0) {
evenList[i] = number;
} else {
oddList[i] = number;
}
答案 1 :(得分:1)
改变这个:
if ( number < 0 ) {
negativeList [ i ] = reader . nextDouble ( ) ;
}
if ( number % 2 == 0 ) {
evenList [ i ] = reader . nextDouble ( ) ;
}
else {
oddList [ i ] = reader . nextDouble ( ) ;
}
到此:
if ( number < 0 ) {
negativeList [ i ] = number ;
}
if ( number % 2 == 0 ) {
evenList [ i ] = number ;
}
else {
oddList [ i ] = number ;
}
答案 2 :(得分:0)
你可能想要这个:
number = reader.nextDouble(); // read the number using Scanner once
count++;
// use it to futher to add to respective arrays
if (number < 0) {
negativeList[i] = number;
}
if (number % 2 == 0) {
evenList[i] = number;
} else {
oddList[i] = number;
}