I have this simple code that works like a small command prompt. User is asked to enter a command and is displayed a message according to what he entered. I just want to make it loop so that the user is asked to enter a command again and again and again until he types 'exit'. How do I do that?
Here is the code:
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
System.out.println("Enter command: ");
String text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
break;
default:
System.out.println("Command not recognized!");
break;
}
command.close();
}
Thank you
I prefer:
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
System.out.println("Enter command: ");
boolean running = true;
while(running){
switch(command.nextLine()){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
running = false;
break;
default:
System.out.println("Command not recognized!");
break;
}
}
command.close();
}
You can put it in a while loop like this:
String text = "";
while(!text.equalsIgnoreCase("exit"))
{
System.out.println("Enter command: ");
text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
break;
default:
System.out.println("Command not recognized!");
break;
}
}
Just let the condition for your while loop be while text <> "exit".
Something like this? I prefer do-while for this type of situation because you probably want to give at least one command.
public static void main(String[] args) {
boolean running = true;
Scanner command = new Scanner(System.in);
do {
System.out.println("Enter command: ");
String text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
running = false; //here?
break;
case "exit":
System.out.println("Application Closed");
running = false; //..or here?
break;
default:
System.out.println("Command not recognized!");
break;
}
} while(running);
command.close();
}
If you want to use a switch, easiest way would probably be a simple infinite while-loop with a label. When the input matches "exit", we just break the loop.
loop:
while (true) {
String text = command.nextLine();
switch (text) {
// ...
case "exit":
break loop;
}
}
while loop is missing in the initial example:
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String command = br.readLine().toLowerCase();
switch (command) {
case "exit": {
// exit here
} break;
default: {
// unrecognised command
}
}
}
}
Related
I've been playing around with basic Java and begun to create a project which includes a user input, system output ad a switch/case statement too. The user inputs a given animal and the system outputs the necessary noise that relates to the animal. At the moment the program asks the user once and then it is finished, however I want the user to be able to input as many animals as they'd like and get appropriate responses. Any help welcome, thanks. (I understand there may be some errors in my code, but I have only really just begun Java.)
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String myString;
System.out.println("Enter your first animal: ");
myString = user_input.next();
loop: switch (myString) {
case "Cow":
System.out.println("Mooo!");
break;
case "Sheep":
System.out.println("Baaaa!");
break;
case "Mouse":
System.out.println("Squeak Squeak!");
break;
case "Horse":
System.out.println("Neighhh!");
break;
case "Goat":
System.out.println("Skreachh!");
break;
case "Fish":
System.out.println("*Bubble Bubble*");
break;
default:
System.out.println("Invalid animal.");
break;
}
}
You need a loop and a condition to stop.
while (true) {
...
switch(...) {
....
case "Stop":
System.out.println("bye bye");
System.exit(0);
break;
}
}
You can also use do-while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter your first animal: ");
myString = input.next();
switch (myString) {
case "Cow":
System.out.println("Mooo!");
break;
........
default:
System.out.println("Invalid animal.");
break;
}
} while (!myString.equals("Stop"));
}
You can get a well-explanation from here and here
I want it to look as if the users input is being responded to by the machine in a loop like sequence that goes back to the original question and allows the previous answers to be accepted as viable answers.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
System.out.println("Please enter a command: ");
String text = input.nextLine();
switch (text) {
case "start":
System.out.println("Machine Started!");
break;
case "stop":
System.out.println("Machine Stopped.");
break;
case "sleep":
System.out.println("In progress: sleeping...");
break;
case "transform":
System.out.println("In progress: transforming...");
break;
default:
System.out.println("Command not recognized");
}
}
}
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
String text;
do {
System.out.println("Please enter a command: ");
text = input.nextLine();
switch (text) {
case "start":
System.out.println("Machine Started!");
break;
case "stop":
System.out.println("Machine Stopped.");
break;
case "sleep":
System.out.println("In progress: sleeping...");
break;
case "transform":
System.out.println("In progress: transforming...");
break;
default:
System.out.println("Command not recognized");
}
} while (!text.equalsIgnoreCase("quit"));
}
}
This should be what you are looking for. The program will abort when user types in quit
I have a homework to implement a simple testing application, below is my current code:
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
System.out.println("Test is done");
}
}
What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?
You can label your while loop, and break the labeled loop, which should be like this:
loop: while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break loop;
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
And the label can be any word you want, for example "loop1".
You need a boolean variable e.g. shouldBreak.
boolean shouldBreak = false;
switch(typing){
case 0:
shouldBreak = true;
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
if (shouldBreak) break;
Put the while inside a function and when you press 0 instead of break just return. For example :
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
func(sc);
System.out.println("Test is done");
}
}
public static void func(Scanner sc) {
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
return; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
}
}
How to terminate inner menu ?
Example Code :
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //used to get input
int option1, option2 = 0;
boolean loop_terminate = true; //flag used to terminate inner while loop
//Main Menu
while (true) {
//Main Menu options
System.out.println("1.Option 1");
System.out.println("2.Option 2");
System.out.println("3.Option 3");
System.out.println("4.Option 4");
System.out.println("5.Exit main menu");
System.out.print("Please enter your choice : ");
option1 = input.nextInt();
switch (option1) {
case 1:
//do something here
break;
case 2:
//do something here
break;
case 3:
while (loop_terminate) {
//Inner menu options
System.out.println("1.Inner Menu option 1");
System.out.println("2.Inner Menu option 2");
System.out.println("3.Inner Menu option 3");
System.out.println("4.Return to Main Menu");
System.out.print("Please enter your choice : ");
option2 = input.nextInt();
switch (option2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
loop_terminate = false; //this will terminate inner menu
break;
default:
System.out.println("Invalid option");
break;
}
}
break; //never forget to add this break statement
case 4:
break;
case 5:
return; //terminate outer menu
default:
System.out.println("Invalid option");
}
}
}
}
I have following code:
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "new":
createNewInstance(tokens);
break;
case "call":
callMethod(tokens);
break;
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
default:
System.out.println("Illegal command!");
break;
}
}
I simply want the program to break out of while loop when user hits ctrl+Z
nextLine() will throw NoSuchElementException when the stream has reached its end. Or you can use in.hasNextLine().
Ctrl+Z to exit the program would be bad, Ctrl+C|Ctrl+D already ends the program execution on terminal, so it would be good the same way you expect users to type in commands, tell them to type exit as the command to EXIT your program and shortcuts like x or e can be used instead of complete word.
How about following code,
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "n":
case "new":
createNewInstance(tokens);
break;
case "c":
case "call":
callMethod(tokens);
break;
case "p":
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
case "e":
case "x":
case "exit":
return;
default:
System.out.println("Illegal command!");
break;
}
}
If return; won't work you can replace that with System.exit(0);
I am running into a problem where Scanner isn't blocking for user input during an indefinite while loop. I've tried using hasNextLine() and that hasn't worked. It just runs the loop infinitely calling displayMenu().
do {
displayMenu();
int response;
while (iStream.hasNextLine()) {
response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
}
while (!done);
I've also tried not using hasNextLine() but I end up with a NoSuchElementException as it runs through perfectly the first time but on the second iteration, it doesn't block for user input.
do {
displayMenu();
int response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
while (!done);
Any thoughts?
The following works fine for me:
private static void displayMenu ()
{
System.out.println ("Menu:");
System.out.println ("\t1: Decode message");
System.out.println ("\t2: Encode message");
System.out.println ("\t3: Display alphabet");
System.out.println ("\t4: Exit");
}
public static void main (String [] args)
{
Scanner scanner = new Scanner (System.in);
boolean done = false;
while (!done)
{
displayMenu();
switch (Integer.parseInt (scanner.nextLine ()))
{
case 1:
System.out.println ("Decoding...");
break;
case 2:
System.out.println ("Encoding...");
break;
case 3:
System.out.println ("Displaying alphabet...");
break;
case 4:
System.out.println("Exitting...");
done = true;
break;
default:
done = false;
}
}
}