2016-10-02 273 views
0

我知道這個問題已經被問過幾次了。隨意將其標記爲重複。無論如何,我寧願問社區,因爲我仍然不確定。在Java中的do-while循環中轉換while循環

我應該在do-while循環中將while循環轉換。 有什麼想法?

public class DoWhile { 
     public static void main(String[] args) { 
      Scanner input = new Scanner(System.in); 
      int sum = 0; 
      System.out.println("Enter an integer " + "(the input ends if it is 0)"); 
      int number = input.nextInt(); 
      while (number != 0) { 
       sum += number; 
       System.out.println("Enter an integer " + "(the input ends if it is 0)"); 
       number = input.nextInt(); 
      } 
     } 
} 
+0

你會幫助你的問題的所有讀者,如果你與你的格式化代碼段縮進和正確的換行符。請考慮編輯。 – Matt

+0

看起來像代碼審查類問題。 http://codereview.stackexchange.com/ –

回答

1

,你不能只是簡單的將任何while循環做while循環,它們之間的主要區別是在做while循環,你有迭代不管條件如何的會發生。

 public class DoWhile { 
      public static void main(String[] args) { 
      int number=0; 
      Scanner input = new Scanner(System.in); int sum = 0; 
      do{ System.out.println("Enter an integer " +"(the input ends if it is 0)"); 
      number = input.nextInt(); 
      sum += number; 
     }while (number != 0) ; 


     } 
     } 
+0

我已經知道這一點,實際上,這是一個來自博士的例子。梁啓超「Java簡介」一書。 – q1612749

+0

我用你的代碼編輯了答案 –

+0

現在更清晰了,謝謝。對不起所有人的麻煩 – q1612749

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

    Scanner input = new Scanner(System.in); 
    int sum = 0; 
    int number = 0; 
    do { 
      System.out.println("Enter an integer " + 
      "(the input ends if it is 0)"); 
      number = input.nextInt(); 
      sum += number; 
    } while(number != 0) 

}}

0
public class DoWhile { 

     public static void main(String[] args) { 

      Scanner input = new Scanner(System.in); int sum = 0; 

      System.out.println("Enter an integer " + "(the input ends if it is 0)"); 
      int number = input.nextInt(); 
      //You need this if statement to check if the 1st input is 0 
      if(number != 0) 
      { 
       do 
       { 
        sum+=number; 
        System.out.println("Enter an integer " + "(the input ends if it is 0)"); 
        number = input.nextInt(); 
       }while(number != 0); 

      } 

    } 

} 
0

你必須告訴程序繼續做在 「做」 事塊。在你自己的情況下,你必須告訴程序繼續這樣做「 System.out.println(」輸入一個整數「+」(輸入結束,如果它是0)「); number = input.nextInt(); sum + = number;「。然後在「而」塊,你必須提供終端聲明,在你自己的情況下,「號!= 0

public class DoWhile { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     int sum = 0; 
     int number;   
     do {  
      System.out.println("Enter an integer " + "(the input ends if it is 0)"); 
      number = input.nextInt(); 
      sum += number; 

     } while (number != 0); 
    } 
    }