简体   繁体   English

Java:为什么此代码有效? For循环,if / else语句

[英]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? > = 8与输入中1的数量有什么关系? How does validatedBinary() - 1 test for the program to only have <= 2 ones? 如何validatedBinary()-1测试程序是否只有<= 2个?

I am particularly curious about how the for loop works within this program in general. 我对整个程序中的for循环如何工作特别好奇。

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 ). 发布程序时,对于任何有效的二进制数字,将打印“已接受。”,对于任何包含不等于“ 1”或“ 0”的字符并且仅拒绝包含7个以上字符的字符串,将显示“ Invalid number。”。 ( validateBinary.length() >= 8 )。 The i == validateBinary.length() - 1 part checks if the index of the for have reached the last character. i == validateBinary.length() - 1部分检查for的索引是否已到达最后一个字符。 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. for循环使我从0到输入字符串的长度-1,并使用它来获取该位置的字符,因此逐个字符地迭代输入字符串。

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. 我相信这可以满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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