2013-10-10 53 views
0
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

不知道那些嵌套的while循環是關於什麼的 – christopher

+0

除了顯示代碼之外,請說明您的問題 – waldrumpus

+0

修改您的代碼以使[SSCCE](http:/ /sscce.org/) – Lion

回答

1
while (!valid) { 

valid從不更新。如果他們想要退出,請將valid設置爲true以及更新word的值。

正如@AnthonyGrist指出的那樣,一起去除while(!valid)循環也將解決此問題。

+0

'while(!valid)'loop看起來完全沒有必要,所以完全刪除它也會解決這個問題 –

+1

它會,但是由於OP做了很少的努力,我沒有太多感覺像重新設計他們的代碼。 – christopher

0

檢查this code 它運行起來

PS:去掉有效的條件也不會導致在進入退出程序的終結!我嘗試過這個。

問題是你正在顯示消息,並立即寫入scan.nextline(),它接受一個空白,這既不是=退出,也是有效的,無論是否設置爲true,將始終初始化爲false,因爲它進入word.equals(..條件