1

到目前为止,我已经运行了这个程序,但我在这部分有库存:程序应该不断提示用户输入一个新单词,直到用户输入一个表示有效二进制数的单词。我知道我想使用一个循环,但我不知道把它放在哪里。

package programming_assignment_1;

import java.util.Scanner;

public class Programming_Assignment_1 {

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        System.out.print("Please imput a binary number : ");
        String binary;
        binary = sc.next();
        boolean isBinary = true;

        char[] values = binary.toCharArray();
        for(int i=0; i<values.length; i++)
        {
                if( (values[i] != '0') && (values[i] != '1') )
                {
                isBinary = false;
                break;
                }
        }
        if(!isBinary)
        {
        System.out.println("this is not a binary number");
        }
        else
        {
            for(int i=0; i<1; i++)
            {
                 String consecutive1s = "111";
               if (binary.indexOf(consecutive1s) != -1)
            {
                System.out.println("accepted");
            }
            else
            {
              System.out.println("rejected");  
            }
            }
        }

    }
}
4

2 回答 2

3

将您的代码置于do...while(..)循环之下。就像是 :

do {
  //read number
  //process number
  // if num valid or operation is finished break the loop using break
} while (condtion);

我会使用您的代码提供解决方案,但您似乎是新手,需要学习 Java 的基本知识。所以我给你只是提示。

于 2012-09-20T06:36:10.900 回答
0
...
public static void main(String[] args) {
    // TODO code application logic here
    boolean accepted = false;
    while(!accepted) {
       Scanner sc = new Scanner(System.in);
       ...

       if(!isBinary) {
           System.out.println("this is not a binary number");
       } else {
           accepted = true;
           ...

       }
       ...

    } // while
} // main

此外,我不确定您的“for”循环 - 它不会向您的程序添加任何内容,因为它只执行一次......

于 2012-09-20T06:39:45.740 回答