samedi 30 octobre 2021

Problem with an if statement in a for loop [closed]

I'm having issues with an if statement that is executing a condition that is not true. I'm writing a program that takes a user's input and parses through it ensuring they have only entered 0s and 1s, or rather a binary number. Here is my code:

String binStr;
for (int i=0; i < binStr.length(); i++) {
        
        if (binStr.charAt(i) == '1') {
            
            System.out.println("Heres a one.");
            count = count + 1;
            
        }
        
        if (binStr.charAt(i) == '0') {
            
            System.out.println("Heres a 0");
            count0 = count0 + 1;
        }else{
            System.out.println("You entered an invalid binary number,"
                    + "please re-enter a valid binary number.");
        }

For some reason it keeps stating that I have entered an invalid binary number even when I use only 1s or 0s. Can anyone help me figure out why this is happening. Thank you.

Aucun commentaire:

Enregistrer un commentaire