0

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

1

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ".

2 Comments

Sir it will just print 4 if i use that i want to print 2 and 4 < i just got extra and < i want my program to determine even numbers of the given number. for example 10 < i want to print 2 and 4 and 6 and 8 and 10. thank you :D
Yes, it will print 4. The first iteration should print 2 and , and the second iteration will print 4, yielding 2 and 4.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.