# how to ask the user to enter a sequence of numbers one at a time

• 10-01-2012, 06:44 PM
dksellou
how to ask the user to enter a sequence of numbers one at a time
Hi.
I have created this little program. It is the solution to exercise 6.17 of Deitel "how to program Java". The program asks the user to add a sequence of numbers and the program tests if it is odd or even...here is what I did. However, I don't know how to ask the user to enter more than one integers (one at a time) before I show the results:

//Exercise 6.17 Solution : EvenOdd.java

import java.util.Scanner;

public class EvenOdd
{
public void evenOrOdd()
{
Scanner input = new Scanner( System.in );

System.out.printf("%s\n%s\n",
"Please enter an integer and I will tell you if it is even or odd: ",
"Enter 0 to exit: ");

int number= input.nextInt();

while (number !=0)
{
if ( isEven( number ) )
System.out.printf( "%d is even\n", number );
else
System.out.printf( "%d is odd\n", number );

number= input.nextInt();
} // end while loop
} // end method evenOrOdd

// return true if number is even
public boolean isEven( int number )
{
return number % 2 == 0;
} // end method isEven
}//end of class EvenOdd

This program output for example is:

enter an integer: 4
4 is even
enter an integer: 5
5 is odd.

how can you program it showing the following:

enter an integer: 4
enter an integer: 5
4 is even
5 is odd.
• 10-01-2012, 09:01 PM
thinkinjava24
Re: how to ask the user to enter a sequence of numbers one at a time
import java.util.Scanner;

public class EvenOdd
{
public static final int NUMBER = 5;
static int[] array = new int[NUMBER];
public static void main(String[] args) {
Scanner input = new Scanner( System.in );

System.out.printf("%s\n%s\n",
"Please enter an integer and I will tell you if it is even or odd: ",
"Enter 0 to exit: ");
for (int i = 0; i < NUMBER; i++) {
System.out.println("Please enter number " + (i+1) + " : ");
array[i]= input.nextInt();
}

for (int i = 0; i < NUMBER; i++) {
isEven( array[i] );
}
}

public static void isEven( int number )
{
if(number % 2 == 0)
System.out.printf( "%d is even\n", number );
else System.out.printf( "%d is odd\n", number );
}
}

this is the code i write. one thing you need to know is that, you have to initialize the number of the integers you want to enter to the system, like the definition of NUMBER which is static in my code. otherwise, it is impossible to realize what you want, personally opinion.
hope it helps.
• 10-02-2012, 12:53 AM
dksellou
Re: how to ask the user to enter a sequence of numbers one at a time
my original post was so clear ...
I also gave an example.

P.S. I am not in Arrays yet....
• 10-02-2012, 06:07 AM
doWhile
Re: how to ask the user to enter a sequence of numbers one at a time