Upvoter
Upvoter

Reputation: 25

get even and odd Integer on a 0-terminated input loop

I am writing a program where user have to enter Integer values, It will continue to accept input and terminated if the user enters 0. Though efficiency is not a problem for this exercise, my code has a lot of loops and too many variables. And I also want to remove the last comma(,)

Code:

int[] even = new int[1000];
int[] odd = new int[1000];
int odd_ctr = 0;
int even_ctr = 0;
while(true){

    System.out.print("Enter number: ");
    int num = input.nextInt();
    if(num == 0) break;

    // even
    if(num % 2 == 0){
        even[even_ctr] = num;
        even_ctr++;
    }

    // odd
    else{
        odd[odd_ctr] = num;
        odd_ctr++;
    }

}


System.out.println("Even");
for(int i = 0; i < even_ctr; i++){
    System.out.print(even[i] + ",");
}

System.out.println("\nOdd");
for(int i = 0; i < odd_ctr; i++){
    System.out.print(odd[i] + ",");
}

Expected output:

Even
2,4,6,8
Odd
1,3,5,7,9

Actual output:

Even
2,4,6,8,
Odd
1,3,5,7,9,    

It will be much appreciated if someone can make my code simpler and shorter.

EDIT: I'm not allowed to use ArrayList

Upvotes: 1

Views: 70

Answers (3)

Flown
Flown

Reputation: 11740

If you want it even shorter, don't store your numbers in arrays. Simply build your result Strings on-the-fly.

StringJoiner even = new StringJoiner(", ");
StringJoiner odd = new StringJoiner(", ");
for(int n = sc.nextInt(); n != 0; n = sc.nextInt()) {
  (n % 2 == 0 ? even : odd).add(Integer.toString(n));
}
System.out.printf("Even: %s%nOdd: %s%n", even.toString(), odd.toString());

If only Strings and arrays are allowed, I would still use only Strings.

String even = "";
String odd = "";
for (int n = sc.nextInt(); n != 0; n = sc.nextInt()) {
  if (n % 2 == 0) {
    even += even.isEmpty() ? Integer.toString(n) : ", " + n;
  } else {
    odd += odd.isEmpty() ? Integer.toString(n) : ", " + n;
  }
}
System.out.printf("Even: %s%nOdd: %s%n", even.toString(), odd.toString());

Upvotes: 1

cjslv
cjslv

Reputation: 377

Here is a single loop solution using String.

String even = "";
String odd = "";

while(true){
    System.out.print("Enter number: ");
    int num = input.nextInt();
    if(num == 0) break;
    // even
    if(num % 2 == 0) even += num + " ";
    // odd
    else odd += num + " ";
}

System.out.println("Even\n" + even.trim().replace(" ", ","));
System.out.println("Odd\n" + odd.trim().replace(" ", ","));

Upvotes: 1

selbie
selbie

Reputation: 104549

You can avoid the trailing comma on each output loop by making sure that i != even_ctr-1

for(int i = 0; i < even_ctr; i++){
    String trail = ((i==even_ctr-1) ? "" : ",";
    System.out.print(even[i] + trail);
}

Upvotes: 1

Related Questions