How to repeat/loop/return to a class

前端 未结 4 1007
独厮守ぢ
独厮守ぢ 2021-01-28 02:22

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 c

相关标签:
4条回答
  • 2021-01-28 02:50

    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.

    0 讨论(0)
  • 2021-01-28 02:53
    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");
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-28 03:01

    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)
    
    0 讨论(0)
  • 2021-01-28 03:04

    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");
    
    
    }
       }
    
    0 讨论(0)
提交回复
热议问题