在Java中的do-while循环中转换while循环

时间:2016-10-02 20:01:28

标签: java loops

我知道已经多次询问过这个问题了。随意将其标记为重复。无论如何,我宁愿问社区,因为我仍然不确定。

我应该在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();
           }
      }
}

5 个答案:

答案 0 :(得分:1)

你不能简单地将任何while循环转换为while循环,它们之间的主要区别在于do 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) ;


       }
       }

答案 1 :(得分: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)

} }

答案 2 :(得分: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);

          }

     }

}

答案 3 :(得分:0)

你必须告诉程序继续在“do”块中执行某些操作。在你自己的情况下,你必须告诉程序继续这样做“     System.out.println(“输入一个整数”+“(输入结束,如果它为0)”); number = input.nextInt();      sum + = number;“。然后在”while“块中,您必须提供终止声明,在您自己的情况下”数字!= 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);
    }
   }

答案 4 :(得分:0)

classInfoClass

{
   public void setinfo()


    {
        int  userage;


        do

        { Console.Write("Please enter your age: ");


         } while (!int.TryParse(Console.ReadLine(),out userage));