How to repeat/loop/return to a class

35,265

Solution 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");
            }
        }
    }
}

Solution 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)
Share:
35,265
user1174394
Author by

user1174394

Updated on July 07, 2022

Comments

  • user1174394
    user1174394 almost 2 years

    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");
            }
        }
    }
    
  • user1174394
    user1174394 over 12 years
    can you be more elaborate? like i said before, im a beginner. I have no experience with c or c++. Where should i put while and what should the code and condition be?
  • user1174394
    user1174394 over 12 years
    Thanks. What does the while(true) statement mean though?
  • G. Bach
    G. Bach over 12 years
    That means "keep repeating forever"; while(condition) {statements} will execute "statements" until "condition" becomes false
  • Adel Boutros
    Adel Boutros over 12 years
    true is always true, So your program will keep taking input until you kill it :)