I have this code that if i enter a number for example :
Enter a number: 1 2 3
output is

but i like it like this:
Enter a number: 1 2 3
Even: 2
Odd : 1 3

Here is My code hope you could help me with this

Edited by JamesCherrill: Code snippets are complete code for sharing - this is a discussion

4 Years
Discussion Span
Last Post by benjo.s.lucas

At the start you don't know how many evens and odds there may be, so you can build up two Strings as you process the numbers and print them only at the end - like this pseudocode:

evens = "", odds = "";
for each number in the input {
   if number is even append it to evens, else append it to odds
print evens and odds


you could split the loop into two. In the first loop print all the even numbers then, in the second loop print all the odd numbers. If you use print rather than println the output will all be on the same line.

Edited by JamesCherrill


You can append anything to a String with the + operator, If the thing you're appending is not a String java will convert it for you...

String s = "The even numbers are ";
s = s + 2;  
s = s + " and " + 4 ;// s is now "The even numbers are 2 and 4"

(You may find the second approach I just added above easier - it's up to you)

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.