jjjhfam
jjjhfam

Reputation: 13

Java For Loop not outputting How (I think) it should

I have no clue how I would research this otherwise, so here this is. I'm trying to create a program that will "flip bits", e.g. the string "00110011" would return "11001100". I tried to make a for loop to output the individual characters so see if getting the characters would work in this way, but it stops without outputting the characters.

public static void main(String[] args) {
    String bitsList = "01010101";
    char[] sepBits = bitsList.toCharArray();
    System.out.println("Array'd");
    int num = bitsList.length();
    System.out.println("Got length");
    for (int count = 0; count == num;) {
                System.out.println(sepBits[count]);
                System.out.println("Outputted " + sepBits[count]);  
    }
}

Upvotes: 0

Views: 70

Answers (3)

Anand Bhosale
Anand Bhosale

Reputation: 7

this might work for you

public static void main(String []args){
    String bitsList = "01010101";
    char[] sepBits = bitsList.toCharArray();
    int num = bitsList.length();

    for ( int i = num - 1 ; i >= 0 ; i-- ) {
        System.out.println("Outputted " + sepBits[i]);
    }    
}

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53859

You never go in your for loop because count is 0 and num is 8 (length of "01010101"). Therefore count == num evaluates to false and the for loop is not entered.

Try to replace your for loop with:

for (int count = 0 ; count < num ; count++) {
    // ...
}

Upvotes: 3

Parttimereaper
Parttimereaper

Reputation: 603

The variable count is not equal to the variable num so the for loop never triggers. I think you are looking for <= not ==. Also you never change the count so the loop will just keep printing the same spot over and over even if you do change this.

Upvotes: 0

Related Questions