Gy30n_W00
Gy30n_W00

Reputation: 5

How to get rid of extra print statement on my loop

Guys i would like to ask how to get rid of the "and" print on my loop

2 and 4 and <

public static void main(String[] args) {
    Methods(5);
}

public static void Methods(int a){

    int loops = a/2;
    int even = 0;

    for(int i = 0; i < loops; i++){
        even+=2;
        System.out.print(even+" and ");
    }
}

it prints

2 and 4 and <<<

Instead i want

2 and 4 <<<

thank you. Please help me i am beginner T_T

Upvotes: 0

Views: 143

Answers (3)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

Before entering the loop check if there is an element, print just the first element. Increment i and then for each remaining element always pre-pend " and " first.

int i = 0;
if (i < loops) {
    even+=2;
    System.out.print(even);
}
i++;
for(; i < loops; i++){
    even+=2;

    System.out.print(" and " + even);
}

This way you avoid all the checking inside the loop.

Upvotes: 0

Simeon Visser
Simeon Visser

Reputation: 122516

You can do:

public static void Methods(int a){
   int loops = a/2;
   int even = 0;

   for(int i = 0; i < loops; i++){
       even+=2;

       System.out.print(even);
       if (i < loops - 1) {
           System.out.print(" and ")
       }
   }

In other words: as long as i is smaller than loops - 1 (which holds during your entire loop except the last step) you would print out " and ". This ensures the last and is not printed when it goes through the loop the last time.

Upvotes: 1

rgettman
rgettman

Reputation: 178333

Test if your index is the last index you would be on, i.e. if i == loops - 1. If so, then just print even instead of even + " and ".

Upvotes: 1

Related Questions