-4

I want to write a simple loop for the program to go back and restart it again.

Just a simple 1 question program. Then the system ask if the user want to do it again. If the user inputs Y ... the program will loop it back to the beginning and run the entire program again. If the user inputs N, it exits.

import java.util.Scanner; // show them as code

public class HowToDoLoop {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");
Faiizii Awan
  • 1,615
  • 1
  • 13
  • 28
DCN
  • 3
  • 1
  • 1
  • 4
  • 1
    `while(true){ break; /* if no */ }` – guleryuz Sep 01 '18 at 16:21
  • 5
    Look into a `while`/ `do-while` loop – GBlodgett Sep 01 '18 at 16:21
  • 7
    I'm voting to close this question as off-topic because: ["3. Questions asking for homework help must include a **summary of the work you've done so far to solve the problem**, and a **description of the difficulty you are having** solving it."](https://stackoverflow.com/help/on-topic). Current state of your question doesn't fulfill these requirements. Use [edit] option to improve it. – Pshemo Sep 01 '18 at 16:23
  • https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html – GBlodgett Sep 01 '18 at 16:24
  • Thank you for everyone's help! Pshemo, this is actually not part of my homework. I'm learning on my own. I watched some youtube videos and kind have a general idea about while loop. I just didn't know what syntax to use to accept Y or N. – DCN Sep 04 '18 at 02:29

2 Answers2

2
while(true){

    System.out.println("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");
    String c = input.nextLine();

   if(c.equalsIgnoreCase("n")){ 
      break;
     }//else continue to loop on any string ;-)

}
Sunder R
  • 1,074
  • 1
  • 7
  • 21
Faiizii Awan
  • 1,615
  • 1
  • 13
  • 28
1
String c = "";
do{
    System.out.println("How much money do you want to have? ");
    double money = input.nextDouble();

    System.out.println("Ok, here is yours $" + money);

    System.out.println("Do you want to continue y or n");
    c = input.nextLine();

}while(c.equalsIgnoreCase("Y"));
Sunder R
  • 1,074
  • 1
  • 7
  • 21