Alex Mccane Alex Mccane - 1 month ago 9
Java Question

Run program by user input using a do while loop

I haven't seem to come across this, hopefully this question hasn't been asked a million times before. I'm having trouble with making a program run again through a do while loop, this would be a very handy piece of code to know but I cant figure it out, any help would be appreciated! This piece of code is just for the purpose of asking this question..

import java.util.Scanner;
public class hello1{
public static void main(String[]args)
{

Scanner scan = new Scanner(System.in);
String s1 = scan.nextLine();

do
{
System.out.println("Do you want to continue? Y/N");
}

while(s1=="Y");
}
}

Answer

You want to do this:

String s1 = "Y";
do
{
    System.out.println("Do you want to continue? Y/N");
    s1 = scan.nextLine();
}while(s1.equalsIgnoreCase("Y"));

You don't want to compare String's using == you should use .equals() or .equalsIgnoreCase()...

Also you should prompt your user for input each time through the loop.