简体   繁体   中英

array error how many odd and even numbers in given terms

  1. I want to output it like so 在此处输入图像描述
  2. my compiler doesn't prompt errors in code I use netbeans apache
  3. when i put how many numbers在此处输入图像描述 ======================================================

        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);
          }
        }    

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());

...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM