1

why is my code here not working im trying to print out every second number in the sequence as hello

public class Generalizations {
    public static void main(String[] args) {


        for(int i=0;i<10;i++)
            System.out.println(i);
        if (i%2==0){
            System.out.println("hello");
        }
    }
}
6
  • put your sysout inside condition Commented Apr 29, 2017 at 7:38
  • 3
    This is one of the best scenarios where indenting your code would have pointed out the issue immediately Commented Apr 29, 2017 at 7:41
  • 2
    you forgot to cover if (i%2==0){ System.out.println("hello"); } in for loop {} .. debug your code . you will know. Commented Apr 29, 2017 at 7:42
  • I am trying to print out the number sequence, and for every even number the words "hello" sorry for the bad layout. im new and didnt understand how it fully works Commented Apr 29, 2017 at 8:28
  • can someone post the solution please? Commented Apr 29, 2017 at 8:30

6 Answers 6

4

To print every second element, print inside the condition as shown below:

for(int i=0;i<10;i++) {//esnure the brace here       
   if (i%2 == 0) {
       System.out.println(i);//prints every second element
   }
}
Sign up to request clarification or add additional context in comments.

Comments

4

You missed the curly braces of for loop.

public class Generalizations {
    public static void main(String[] args) {


        for(int i=0;i<10;i++){
            System.out.println(i);
            if (i%2==0){
                System.out.println("hello");
            }
        }
        }
    }

Comments

2

If you want to print every second number as hello, you can try below looping :

for(int i=1;i<=10;i++){            
        if (i%2==0){
            System.out.println("hello");
        }else{
            System.out.println(i);
        }
    }

Comments

2

use this

public class Generalizations {
public static void main(String[] args) {


    for(int i=0;i<10;i++){
        System.out.println(i);
        if (i%2==0){
            System.out.println("hello");
        }
    }
}

Comments

1

It's because the 'for' loop is missing the curly braces thus only one line below it is printed. If you want more than one statements to be executed in the 'for' loop, add a curly brace before the statements start and after your block of statements end. I believe your code does currently print one Hello though, doesn't it? That is because when the if statement runs the value of i is 10 thus fulfilling the if condition.

Comments

0

Your missing a curly brace at the start of your for loop.

for(int i=0;i<10;i++)

should be

for(int i=0;i<10;i++){

Comments

Your Answer

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