-1

Hi im trying to make a program which when you run acts like your talking to a robot who will asks some questions about your self but I have included a part where it asks you if you would like to continue but then i get stuck on how to make the program continue running or closing if the user inputs 'NO'. This is all my code so far:

/********************
*Husnain Sheraz
*06/08/17
*To test knowledge
*Home
********************/




import java.util.concurrent.TimeUnit;
import java.util.Scanner;
public class reviseJava{

    public static void main(String[] args)
    throws InterruptedException {
        //Introduction just saying my name.
        printWithDelays("Hello my name is HUS9.EXE", TimeUnit.MILLISECONDS, 100);

        TimeUnit.SECONDS.sleep(2);

        //Asking user's name and printing it.

        //start a new line
        System.out.println("");

        Scanner scan = new Scanner(System.in);

        //A prompt for the user to enter his name.
        printWithDelays("What's your name?", TimeUnit.MILLISECONDS, 100);

        //reads the next letters (string) the user presses before hitting enter.
        String usersName = scan.nextLine();

        //printing out the word hello and what ever the user inputted as his/hers name.
        printWithDelays("Hello " + usersName, TimeUnit.MILLISECONDS, 100);

        TimeUnit.SECONDS.sleep(1);


        printWithDelays(" i'm going to ask you some basic questions about yourself. If you would like to continue please type 'YES' if you would not like to continue please type 'NO'.", TimeUnit.MILLISECONDS, 100);

        printWithDelays("Would you like to continue?", TimeUnit.MILLISECONDS, 100);

        String answer = scan.nextLine();

    }














public static void printWithDelays(String data, TimeUnit unit, long delay)
        throws InterruptedException {
    for (char ch:data.toCharArray()) {
        System.out.print(ch);
        unit.sleep(delay);
    }
    }

}

4 Answers4

1

You can use

System.exit(0) 

When it matches to 'No'

Akash
  • 587
  • 5
  • 12
  • @SchoolBoy thanks to you both I got my code working just how i needed it to. I added the line of code if (answer.equals("NO")) System.exit(0); – Husnain Sheraz Aug 07 '17 at 16:42
0

you can put System.exit(0); inside an if statement to end your program

ja08prat
  • 154
  • 10
0

You should check the value with an if statement:

if(answer.equals("NO")){
    return;
}

This will quit the program if the user types in "NO", otherwise it continues.

Kaamil Jasani
  • 464
  • 5
  • 11
0

Have your code run inside while loop

  public static void main(String[] args){
  Scanner scan = new Scanner(System.in);
    String input="";

    While(!(input=scan.nextLine()).equals("NO")){

    // your code goes here
    System.out.println("input not NO");
    }
}
Noman Khan
  • 920
  • 5
  • 12