Using a loop to prevent a program from closing? Help greatly appreciated :)
Hi guys, I've been working on this assignment I got and have hit a roadblock. My program prompts the user to enter a number between 0-6, each with a corresponding option. I want the program to keep running until the user selects 0, the exit option. I'm just wondering how I would achieve this? Here's my code below so far. Any help would be greatly appreciated :)
package ca1;
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass extends UserInput {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
UserInput ui = new UserInput(); // Declaring object to store user input
Scanner input = new Scanner(System.in);
ArrayList<String> library = new ArrayList <>();
Song s;
//initial prompt Menu
System.out.println("Welcome");
System.out.println("........ \n");
System.out.println("Press 0 to Exit\n");
System.out.println("Press 1 to View All Songs\n");
System.out.println("Press 2 to Add a Song\n");
System.out.println("Press 3 to Remove a Song\n");
System.out.println("Press 4 to Edit a Song\n");
System.out.println("Press 5 to Count Songs\n");
int opt=input.nextInt();
//add to array list
library.add("Track 1");
library.add("Track 2");
library.add("Track 3");
library.add("Track 4");
library.add("Track 5");
while (opt > 0){
//if statements
if(opt==0)
{
System.out.println("Goodbye!");
}
else if (opt==1)
{
System.out.println("Your Library:");
System.out.println(library);
}
else if(opt==3)
{
System.out.println("Please name your new track");
System.out.println(library);
}
else if(opt==4)
{
System.out.println("Please select what you would like to remove from your library");
System.out.println(library);
}
else if(opt==5)
{
System.out.println("What song would you like to edit?");
System.out.println(library);
}
else if(opt==6)
{
System.out.println(library);
}
else
{
System.out.println("Incorrect Entry");
}
}
}
}
Re: Using a loop to prevent a program from closing? Help greatly appreciated :)
Use a do-while statement. While the variable or boolean is true, run the loop.
Re: Using a loop to prevent a program from closing? Help greatly appreciated :)
use code tags and read the forum rules please.
Re: Using a loop to prevent a program from closing? Help greatly appreciated :)
too many if, else if try
Code:
switch(opt){
case 1 : System.out.println("whatever"); break;// like this
case 2 : System.out.println(); break;
case 3 : System.out.println(); break
case 4 : System.out.println(); break;
default : sdfsdfsdsdf break;
Re: Using a loop to prevent a program from closing? Help greatly appreciated :)
Quote:
Originally Posted by
pakupakuman
Use a do-while statement. While the variable or boolean is true, run the loop.
Worked perfectly, thank you!
Re: Using a loop to prevent a program from closing? Help greatly appreciated :)