-4

So saying I had this Loop

for (int i = 0; i < InfomationText.length; i++) {
       System.out.println("Hello World");
}

But every second time it loops 1 value I need the string to "Hello World1"

Eg

  • Index 0: = Hello World
  • Index 1: = Hello World1
  • Index 2: = Hello World
  • Index 3: = Hello World1

Thanks in advance.

  • 2
    Do you know how to check if `i` is even? Then you can just decide what's printed. – Carcigenicate Sep 06 '18 at 16:51
  • I can strongly recommend reading through the [java basics](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html) documentation. It doesn't take super long, and gives you the basics that let you figure out what the language can even do at the fundamental level, such as here. You can easily write something that checks whether "right now" is "every second time", but not if you haven't read through what basics the language supports. – Mike 'Pomax' Kamermans Sep 06 '18 at 16:54
  • possible duplicate of https://stackoverflow.com/questions/7342237/check-whether-number-is-even-or-odd although to be fair that's kind of x-y. This problem could be solved by adding i++; and then System.out.println("Hello World1"); – Jeutnarg Sep 06 '18 at 16:55
  • homework? search for fizbuz on the net... – rdmueller Sep 06 '18 at 16:56

2 Answers2

1

Like Cargigenicate's comment says, you can check if i is odd or even:

for (int i = 0; i < 10; i++) {
    if(i % 2==0){
        System.out.println("Hello World");
    }
    else{
        System.out.println("Hello World1");
    }
}
Acapulco
  • 3,373
  • 8
  • 38
  • 51
1

I'd add something like this to the loop body:

if(i%2 == 0) {
    System.out.println("Hello World");
} else {
    System.out.println("Hello World1");
}

Alternately, you could append to your string in the if, and then have one System.out.println():

String greeting = "Hello World";
if(i%2 == 1) {
    greeting = greeting + "1";
}
System.out.println(greeting);
Claire Nielsen
  • 1,881
  • 1
  • 14
  • 31