簡體   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;

            }
        }
    }
 }
}

該代碼旨在檢測數字是否為二進制。 如果數字是二進制的,則設計為拒絕包含兩個以上數字的數字,否則接受該數字。 > = 8與輸入中1的數量有什么關系? 如何validatedBinary()-1測試程序是否只有<= 2個?

我對整個程序中的for循環如何工作特別好奇。

運行此代碼后,它僅要求輸入一個,然后結束。 您如何重申它?

發布程序時,對於任何有效的二進制數字,將打印“已接受。”,對於任何包含不等於“ 1”或“ 0”的字符並且僅拒絕包含7個以上字符的字符串,將顯示“ Invalid number。”。 ( 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;
          }
        }
      }
    }
  }
}

嘗試使用此版本的代碼。

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

我相信這可以滿足您的要求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM