2016-10-02 277 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); 
    } 
    }