执行循环以创建读取用户输入以重复或退出程序Java

时间:2014-04-09 02:30:12

标签: java loops do-while

这是我的第一篇文章。

使用扫描仪课程,我试图让用户输入选择重复该程序或退出。事情是我的Do循环语句重复程序,即使Do循环为假并且应退出程序也不会退出。

// loop repeat or quit
do { 
 //initialize variable
  int integer;
  int x = 1;
  int factorial = 1;

System.out.print("Please enter an integer \n");
integer = getInt.nextInt();
//loop for factorial 
//multiple each increment until it reaches the integer
while (x <= integer) {

  factorial *= x;
  x++;

 }; // factorial=x*x
  System.out.println("the factorial of the integer " + integer + " is " + factorial);

 System.out.print("do you want to quit? y or n \n");
 quit = getString.next();


 } while(quit != yes);


 System.exit(0);
 }

3 个答案:

答案 0 :(得分:0)

你的代码中有一些错误,所以我重写了一点,并使用了正确的函数,你使用了不正确的函数。

    public static void main(String args[])
    {
    // Scanner is used to take in inputs from user
    Scanner scan = new Scanner (System.in);
    String quit = "";

    // loop repeat or quit
    do { 
        //initialize variable
        int integer = 0;
        int x = 1;
        int factorial = 1;

        // User needs to enter integer, or it'll throw exception.
        System.out.println("Please enter an integer");
        integer = scan.nextInt();

        //loop for factorial 
        //multiple each increment until it reaches the integer
        // factorial = x!
        while (x <= integer) {
            factorial *= x;
            x++;
        }; 

        System.out.println("the factorial of the integer " + integer + " is " + factorial);
        System.out.println("do you want to quit? y or n");
        quit = scan.next();

         // if quit is NOT equal to y, we do it again
     } while(!quit.equals("y"));

     System.exit(0);
}

我希望评论有所帮助:)

答案 1 :(得分:0)

我已经编辑了您的代码,现在它已经运行了。

供将来参考:添加更全面的代码段,以便您的代码查看者可以更轻松地发现错误。

问题:无法保证用户只输入y而没有任何空格。这个问题的简单解决方案是使用字符串方法contains()。我修改了你的循环,这样如果用户输入y,程序将退出并且现在可以正常工作。让我知道这是否有效且编码愉快!

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        String quit ="";

        do { //initialize variable
            int integer; int x = 1; int factorial = 1;

             System.out.print("Please enter an integer \n");
             integer = in.nextInt();
             //loop for factorial 
             //multiple each increment until it reaches the integer
             while (x <= integer) {

               factorial *= x;
               x++;

              }; // factorial=x*x
               System.out.println("the factorial of the integer " + integer + " is " + factorial);

              System.out.print("do you want to quit? y or n \n");
              quit = in.next();


              } while(!quit.contains("y"));


              System.exit(0);


    }

答案 2 :(得分:-1)

不应该是

while(quit != "y");

我也不明白为什么你使用System.out.print();然后使用\ n当有一个非常好的System.out.pritnln();

另外,因为我们正在处理字符串.nextLine();对于扫描仪来说已经足够了。 (你还必须声明String退出。)