How to repeat/loop/return to a class

我的梦境 提交于 2019-12-02 17:45:38

问题


Im a beginner with java and i am following tutorials by Thenewboston on youtube. I wanted to go to a bit more advanced (in my opinion... but not really) things. So heres the code. I want to make it so that it repeats to the beginning so i can enter another number without restarting the program. I believe i have to use the return command but i am not sure where and how to. Thank you!

import java.util.Scanner;

class apples {

    public static void main(String args[]) {

        Scanner alex = new Scanner(System.in);
        Double test;
        test = alex.nextDouble();

        if (test == 9) {
            System.out.println("eat");
        } else {
            System.out.println("do not eat");
        }
    }
}

回答1:


import java.util.Scanner;

class apples{

    public static void main(String args[]){

        Scanner alex = new Scanner(System.in);
        Double test;
        while(true) {
            test = alex.nextDouble();
            if (test == 9){
                System.out.println("eat");
            }else{
                System.out.println("do not eat");
            }
        }
    }
}



回答2:


like in C or C++ you could use a while statement , askin after the execution is the user want go to exit or not

while (answer){
  // ...code...
}

also you could use do..while

do{
  // ...code...
}while(condition)



回答3:


Wrap your code around while loop and use break to come out of loop if your condition is true.

while((alex.hasNext()))
   {
    test = alex.nextDouble();

    if (test == 9){
        System.out.println("eat");
        break;

}else{
        System.out.println("do not eat");


}
   }



回答4:


Something like this:

Double test;
Scanner alex = new Scanner(System.in);
  while (alex.hasNextDouble()) {
     test = alex.nextDouble();
         if (test == 9){
              System.out.println("eat");
               continue;

          }else{
                 System.out.println("do not eat");
                  break;

     }

  } 

Note: Assuming all inputs are double, otherwise this program may fail.

This is not perfect example too, because even though you don't say continue while loop iterates. It may be good example for break.



来源:https://stackoverflow.com/questions/9040122/how-to-repeat-loop-return-to-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!