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

时间:2015-12-03 03:21:41

标签: java

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;

            }
        }
    }
 }
}

该代码旨在检测数字是否为二进制。如果数字是二进制数,则设计为拒绝该数字(如果它包含的数字超过2个),否则接受该数字。 &gt; = 8与输入中1的数量有什么关系? validatedBinary() - 1如何测试程序只有&lt; = 2个?

我特别好奇for循环在这个程序中的工作原理。

运行此代码后,它只询问输入一,然后结束。你如何重申?

2 个答案:

答案 0 :(得分:2)

当您发布的程序打印出“已接受。”时,对于任何有效的二进制数,打印“无效数字。”表示任何包含不等于“1”或“0”的字符的字符串,并且仅拒绝更多字符串超过7个字符(validateBinary.length() >= 8)。 i == validateBinary.length() - 1部分检查for的索引是否已到达最后一个字符。 for循环使我从0变为输入字符串-1的长度,并使用它来获取该位置的字符,因此逐字符地迭代输入字符串。

该程序的修改版本可满足您的要求:

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;
          }
        }
      }
    }
  }
}

答案 1 :(得分:1)

尝试此版本的代码。

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;
        }
    }
}
}

我相信这符合你的要求。