我进入循环时无法退出

时间:2013-10-10 15:02:38

标签: java loops infinite-loop

import java.util.*;

public class ConvertBinaryToInteger{
public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    final String EXIT="exit";


    System.out.println("This program will convert a binary into an integer.");
    System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
    String word=scan.nextLine();

    while(!word.equals(EXIT)){

            while(!word.equals(EXIT)){
                boolean valid = false;
                while (!valid) {
                    System.out.println("Enter a binary number: ");
                    String binary = scan.next();
                    boolean isBinary = true;//first convert the 'binary' string into a char array and check for each char whether it is zero or one
                    char[] bits = binary.toCharArray();

                    for(int j=0; j<bits.length; j++){//read the inputs

                        if( (bits[j] != '0') && (bits[j] != '1') ){//check the inputs
                            isBinary = false;
                            break;
                        }
                    }
                    if(!isBinary){//not binary
                        System.out.println("This is not a binary number.");
                        System.out.println("Please enter a number that contains only 1's and 0's.");
                        System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
                        word=scan.nextLine();
                    }
                    else{//binary
                        int integer = 0;
                        int temp;
                        int i = 0;
                        temp = Integer.parseInt(binary);

                        while (temp != 0){
                            int r = temp % 10;
                            double value = r * Math.pow(2, i);
                            i++;
                            integer = (int) (integer + value);
                            temp /= 10;
                        }
                        System.out.println("Integer of " + binary + " is " + integer+".");
                        System.out.println("Enter "+EXIT+" to exit program. Press enter to continue.");
                        word=scan.nextLine();
                    }   
                    System.out.println();
                    scan = new Scanner(System.in);
                }


            }



        }System.out.println("Program ended.");
    }

}
输入正确的二进制文件后

无法退出。请帮我改变程序...... 如果您没有首先退出,则无法结束该计划..

2 个答案:

答案 0 :(得分:1)

while (!valid) {

valid永远不会更新。如果他们想要退出,请将valid设置为true,并更新word的值。

正如@AnthonyGrist所指出的,完全删除while(!valid)循环也可以解决此问题。

答案 1 :(得分:0)

检查this code 它正在运行

PS:删除!有效条件也不会导致程序在进入退出时终止。我尝试过这个。

问题是你正在显示消息并且还立即写入scan.nextline(),它接受一个空白,这既不是=退出也是有效无论是否设置为true,将始终初始化为false,如它进入word.equals(..条件。