146k views
3 votes
Create a Java program that takes a list of integers as input from the user and outputs whether the list contains all even numbers, odd numbers, or neither. The input begins with the number of integers that will be stored in the list followed by the numbers to be stored in the array.

1 Answer

2 votes

Answer:

This question is answered in Java programming language

import java.util.Scanner;

public class Main{

public static void NumberTypes(int[]myarray){

int evennum = 0; int oddnum = 0;

for(int i = 1;i<=myarray[0];i++){

if(myarray[i]%2==0){ evennum++;}

else{ oddnum++;}

}

if(evennum == 0 && oddnum!=0){ System.out.print("Odd List"); }

else if(evennum != 0 && oddnum==0){ System.out.print("Even List"); }

else if(evennum != 0 && oddnum!=0){ System.out.print("None"); }

}

public static void main(String [] args){

int num;

Scanner input = new Scanner(System.in);

System.out.print("Length of list: ");

num = input.nextInt();

int [] myarray = new int[num+1];

myarray[0] = num;

for(int i = 1;i<num+1;i++){

myarray[i] = input.nextInt();

}

NumberTypes(myarray);

}

}

Step-by-step explanation:

This question is answered in Java and it uses function to answer the question.

The name of the function is NumberTypes

The program starts here

import java.util.Scanner;

public class Main{

The function NumberTypes starts here

public static void NumberTypes(int[]myarray){

This line initializes even and odd to 0

int evennum = 0; int oddnum = 0;

The following iteration iterates through the array

for(int i = 1;i<=myarray[0];i++){

This checks if current array element is even. If yes, even variable is incremented by 1

if(myarray[i]%2==0){ evennum++;}

This checks if current array element is odd. If yes, odd variable is incremented by 1

else{ oddnum++;}

}

If even is 0 and odd is not 0. The list is purely even number

if(evennum == 0 && oddnum!=0){ System.out.print("Odd List"); }

If odd is 0 and even is not 0. The list is purely odd number

else if(evennum != 0 && oddnum==0){ System.out.print("Even List"); }

If even and odd are not 0. The list is purely neither even nor odd

else if(evennum != 0 && oddnum!=0){ System.out.print("None"); }

}

The main method begins here

public static void main(String [] args){

This declares num; the length of array as integer

int num;

Scanner input = new Scanner(System.in);

This prompts the user for length of the array

System.out.print("Length of list: ");

This gets the length of the array

num = input.nextInt();

This declares the array as integer

int [] myarray = new int[num+1];

This initializes index 0 as the length of the array

myarray[0] = num;

The following iteration gets input for the array

for(int i = 1;i<num+1;i++){

myarray[i] = input.nextInt();

}

This calls the function

NumberTypes(myarray);

}

}

User Mihaela
by
6.5k points