user3272643
user3272643

Reputation: 5

How to restart the code after a loop

import java.util.Scanner; 

public class Testing { 

    public static void main(String[] args) {

        int i = 0, j = 0;

        while(i>=0){
        Scanner input=new Scanner(System.in);

        System.out.println("Enter a number:");        
        i = input.nextInt();

            for(;i>0;i--){

                for (j=i; j>0; j--){

                 System.out.print("*");
                 }
                 System.out.println(" ");
            }
        }  
    }
}

is the code, after I input the number and it prints the result, it should ask me if I want to try again or exit as choice 1.again 2.exit, I'm not sure how to make the code restart from the beginning. Any help would be good.

Upvotes: 0

Views: 132

Answers (7)

M7Jacks
M7Jacks

Reputation: 124

Try something like this:

while(true){
      //get input
    for(){
        //process output
    }
    //get input for continue or exit
    if(input is exit){
        //break out of while loop
    }
}

Upvotes: 0

Alex Johnson
Alex Johnson

Reputation: 534

do {

//get user input
if (input==2){
System.exit(1);
}
//
else{
System.out.print(input);
}
//
} while(!done);

You just need to put your existing code into another loop, and then you can set the condition for when exit is desired to a number of different exit methods.

System.exit(1);
done=false;

Upvotes: 0

Hilydrow
Hilydrow

Reputation: 918

To represent the behavior you're asking for (since you don't want to ask the user to continue the first time), I would suggest using a do {} while; loop as such:

int redo = 0;
do {
    //Initialize your variables
    //Read the Input
    //Process the Input

    System.out.println("Enter 1 to do it again:");
    redo = input.nextInt();
} while(redo == 1);

Upvotes: 1

Alberto Solano
Alberto Solano

Reputation: 8227

Use a while loop. Enclose what you want to 'restart' from the beginning in a while loop.

As condition of the loop, use a boolean value that you update once you want to break the loop and close the program. E.g.: when the user presses a key, your loop will end.

Upvotes: 0

Girish
Girish

Reputation: 1717

you can use the switch case to do that like

 String choice;
        switch (choose) {
            case 1:  choice = "start again ";
                     break;
            case 2:  choice = "exit";
                     break;

            default: choice = "Invalid match";
                     break;
        }

and based on the value of choice you can run your loop

Upvotes: 0

DwB
DwB

Reputation: 38300

When you need a loop, use a loop. If you need two nested loops, then use 2 nested loops.

A psuedo-code like example:

loopy
{
  ask for input

  loopy
  {
      process input
  }
}

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

Enclose everything in another loop. This way you can 'restart it' from the beginning.

Upvotes: 0

Related Questions