Program for Odd/Even output only giving 1 answer

2019-09-12 08:26发布

问题:

I'm stuck on an assignment needs the program to accept multiple numbers and then output "Yes" if odd and "No" if even, and can't figure out how to make the program accept more than 1 int and then output the correct println. This is my code so far.

import java.util.Scanner;
class odd{
  public static void main(String args[]){

    Scanner in = new Scanner(System.in);

    int[] numbers = new int[10];
    for(int i = 0; i < 10; ++i) {
      numbers[i] = in.nextInt();

      if(i % 2 == 0 )
         System.out.println("Yes");
      if( i % 2 == 1 )
         System.out.println("No");
    }
  }
}

回答1:

First store all your numbers in an array. Later loop it.

Instead of checking index value like if(i % 2 == 0 ), check the entered number if(numbers[i] % 2 == 0).

  int[] numbers = new int[10];

  //storing all the numbers in an array
  for(int i = 0; i < 10; ++i)
      numbers[i] = in.nextInt();

  //checking each one
  for(int i = 0; i < numbers.length; ++i) {
     if(numbers[i] % 2 == 0 )
         System.out.println("No");//even
     if(numbers[i] % 2 == 1 )
         System.out.println("Yes");//odd
  }

Output:

1 4 3 6 7 8 9 0 2 3 No Yes No Yes No Yes No Yes Yes No



回答2:

I'm going to guess that you mean numbers[i] % 2, rather than i % 2. Otherwise, you're not using the values you are reading from System.in.

Note that the array is unnecessary, since you never use the array again: just declare a variable in the loop. Also, you don't need to check <something> % 2 twice: the conditions are mutually exclusive. You can also just read until in.hasNextInt() is false:

while (in.hasNextInt()) {
  int v = in.nextInt();
  if (v % 2 == 0) {
    System.out.println("Yes");
  } else {
    System.out.println("No");
  }
}