0
  1. I want to output it like so enter image description here
  2. my compiler doesn't prompt errors in code I use netbeans apache
  3. when i put how many numbers enter image description here ======================================================

        public class NewClass 
        {
          public static void main(String[] args)
          {
            int n = 0;
            int EvenNo;
            int OddNo;
            Scanner sc = new Scanner(System. in);
     
            System.out.println("How many numbers will be entered?");
            n = sc.nextInt();
            int a[]=new int[n];
        
            //I think Im missing some code here

            System.out.println("Enter " + n + " Elements Separated by Space >> " );
            String input;
            input = sc. nextLine();
            String[] tokens = input.split(" ");
            int[] inputNumbers = new int[tokens.length];
 
            EvenNo = OddNo = 0;

            for(int i = 0; i < tokens.length; i++)
            {
               inputNumbers[i] = Integer.parseInt(tokens[i]);

               if(inputNumbers[i] % 2 == 0 && inputNumbers[i] != 0)
               EvenNo++;
 
               else if(inputNumbers[i] % 2 != 0)
               OddNo++;
            }
               System.out.print("\n");
               System.out.println("The number of Even Numbers >> " + EvenNo);
               System.out.print("The number of Odd Numbers >> " + OddNo);
          }
        }    
John Nope
  • 3
  • 3

2 Answers2

1

You should convert the string format of scanner input to an integer, using Integer.parseInt()

....
System.out.println("How many numbers will be entered?");
n = Integer.parseInt(sc.nextLine());

...
0

Here is the problem. You have this...

System.out.println("How many numbers will be entered?");
n = sc.nextInt();

...which is later followed by this...

input = sc. nextLine();

Long story short, nextLine() does not play well with the other next***() methods of the scanner. You can read here for more info - https://stackoverflow.com/a/13102066/10118965

The easiest way to solve your problem would be to do this

System.out.println("How many numbers will be entered?");
n = sc.nextInt();
sc.nextLine();

That's probably the least painful way to solve this. But in the future, you can avoid this problem entirely if you only use nextLine(). Those convenience methods are nice, but as you see, they can cause you problems if you don't know their particular nuances.

davidalayachew
  • 304
  • 4
  • 13