简体   繁体   中英

Java: Why does this code work? For loop, if/else statement

import java.util.Scanner;

public class WeirdoBinary
{

public static void main(String[] args)
{

  String validateBinary;

  Scanner scan = new Scanner(System.in);
  System.out.print("Enter a binary number > " );
  validateBinary = scan.nextLine();

  for (int i = 0; i <= validateBinary.length() - 1; i++)
  {

    if (validateBinary.length() >= 8)
      {
      System.out.println("Rejected.");
      break;
        }
       char binary = validateBinary.charAt(i);
        if (binary != '1' && binary != '0')
        {
            System.out.println("Invalid number.");
            break;
        }
        else
        {
            if(i == validateBinary.length() - 1)
            {
                System.out.println("Accepted. " );
                break;

            }
        }
    }
 }
}

The code is designed to detected whether the number is binary or not. If the number is binary, it is designed to reject the number if it contains more that 2 one's, and accept it otherwise. What does >= 8 have anything to do with the number of of 1's in the input? How does validatedBinary() - 1 test for the program to only have <= 2 ones?

I am particularly curious about how the for loop works within this program in general.

After running this code, it only asks for input one, and then ends. How do you make it reiterate?

The program as you post it prints "Accepted. " for any valid binary number, prints "Invalid number. " for any string that contains a character not equals to '1' or '0' and only rejects the strings with more than 7 characters ( validateBinary.length() >= 8 ). The i == validateBinary.length() - 1 part checks if the index of the for have reached the last character. The for loop makes i go from 0 to the lenght of the input string - 1, and uses it to get the characters in that position, so iterates character by character the input string.

This modified version of the program address your requirements:

import java.util.Scanner;

public class WeirdoBinary {

  public static void main(String[] args) {

    String validateBinary = "  ";

    Scanner scan = new Scanner(System.in);

    while(validateBinary.length() > 0) {
      System.out.print("Enter a binary number or enter to finish > " );
      validateBinary = scan.nextLine();
      int ones = 0;

      for (int i = 0; i <= validateBinary.length() - 1; i++) {    

        // Checks that the string is not more than 7 characters long
        if (validateBinary.length() >= 8) {
          System.out.println("Rejected.");
          break;
        }

        // Gets the character at the i position
        char binary = validateBinary.charAt(i);

        // Counts the '1' characters
        if (binary == '1')
          ones++;

        // Verifies that has not more than 2 '1's
        if(ones > 2) {
          System.out.println("Rejected.");
          break;
        }

        // Verifies that only contains '1' or '0'
        if (binary != '1' && binary != '0') {
          System.out.println("Invalid number.");
          break;
        } else {
          // If i reach the end of the string the number is ok
          if(i == validateBinary.length() - 1) {
            System.out.println("Accepted. " );
            break;
          }
        }
      }
    }
  }
}

try this version of your code.

import java.util.Scanner;

public class WeirdoBinary {

public static void main(String[] args) {
    String validateBinary;
    int i, countOne;
    boolean insertAnotherValue = true;
    char binary;
    Scanner scan = new Scanner(System.in);
    while (insertAnotherValue == true) {
        System.out.print("Enter a binary number > " );
        validateBinary = scan.nextLine();

        //this if is not needed, you could remove it, 
        //its just here to check if the not more than 8 bits long

        //if (validateBinary.length() >= 8) {
        //  System.out.println("Rejected.");
        //} 
        //else {
        countOne = 0;
        for (i = 0; i < validateBinary.length() ; i++) {    
            binary = validateBinary.charAt(i);
            if (binary == '1') {
                countOne++;
            } 
            if ((binary != '1' && binary != '0') || countOne > 2) {
                break;
            }
        }
        //}

        if(i == validateBinary.length()) {
            System.out.println("Accepted. ");
        } else {
            System.out.println("Rejected. ");
        }

        System.out.println("\ninsert another value? (y/n)");
        if (scan.nextLine().equalsIgnoreCase("y") ) {
            insertAnotherValue = true;
        } else {
            insertAnotherValue = false;
        }
    }
}
}

i believe this fulfills your requirement now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM