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
Related
Here's my code:
import java.util.Scanner;
// I want to call the menu function in my driver class and in a do while loop .
public class Driver {
public static void main(String[] args) {
do {
Scanner scanner = new Scanner(System.in);
char choice = scanner.next().charAt(0);
} while (choice == 'Q');// How to exit the menue
}
static void createNewEmployee() {
System.out.println("What is the name of employee?");
}
static void process() {
char choice;
switch (choice) {
case 'N':
System.out.println("new employee");
createNewEmployee();
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
default:
System.out.println("Error");
}
}
}
Change while (choice == 'q') into while (choice != 'q'). Think of it like "if the user presses anything apart from 'q', carry on".
I think this will help you!!
public static void main(String[] args) {
char choice;
do {
Scanner scanner = new Scanner(System.in) ;
System.out.print("Press Any Key: N -- New, P -- Paycheck, R -- Raise Wages,-- List Employee, Q -- Quit: ");
choice = scanner.next().charAt(0);
process(choice);
} while(choice !='Q');
}
static void process(char choice) {
switch (choice) {
case 'N':
System.out.println("new employee");
break;
case 'P':
System.out.println("Compute paychecks");
break;
case 'R':
System.out.println("Raise Wages ");
break;
case 'L':
System.out.println("List Employees ");
break;
case 'Q':
System.out.println("Thanks!!");
break;
default:
System.out.println("Error");
}
}
I have a question as to how I can perform several checks inside the switch-case? I need to do a couple of checks in case 2, but adding a second if block, my application does nothing, it just hangs. What was I wrong about?
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
In the second case statement, you should read the next input only once:
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String next = inputCommand.readLine();
if (next.equals("su")) {
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (next.equals("an")) {
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
}
Your first if statement is swallowing the input line, so the second if statement has nothing to read.
Just store the line after reading it once :
String readLine = inputCommand.readLine();
if (readLine.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (readLine.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
Everytime you do a inputCommand.readLine() the Programm waits for an input on your side. You can't compare a single input like you did in this example. The best way would be to save the input in a variable and then perform your checks. Something like this would work (not tested):
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String input = inputCommand.readLine();
if (input.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (input.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
Replace if with else if
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
I assumed this is a basic program for learning purposes so i tried to keep it simple.
1.Don't forget to close Scanner class.
2.always convert digit input to LowerCase(consider case of 'q' vs 'Q')
3.everytime you execute "scanner.nextLine()" your program will halt and wait for input from source(in that case System.in configured to take input from keyboard)
4.System.out.println will print '\n' to the screen at the end of its input causing it to create a new line, you can use this char inside your string to save code lines.
Complete Code:
import java.util.Scanner;
import java.io.IOException;
public class MyClass {
public static void ShowMenu()
{
System.out.println("\nInstruction:");
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println("q -- Quit Program");
}
public static void ProductMenu()
{
System.out.println("Select product to add into your basket");
System.out.println();
System.out.println("ba -- Basketball");
System.out.println("fi -- Fiat 500");
System.out.println("ip -- Iphone");
System.out.println();
}
public static void Exit(Scanner sc) {
sc.close();
System.out.println("You've exited the program. goodbye!");
System.exit(1);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String inputCommand = null;
while (true) {
ShowMenu();
switch (inputCommand = scanner.nextLine().toLowerCase()) {
case "1":
System.out.println("you entered 1");
break;
case "2":
ProductMenu();
inputCommand = scanner.nextLine(); //should block
if (inputCommand.equals("ba")){
System.out.println("Basketball added.");
}
if (inputCommand.equals("fi")){
System.out.println("Fiat 500 added.");
}
if (inputCommand.equals("ip")){
System.out.println("Iphone added.");
}
break;
case "q":
Exit(scanner);
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
}
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
}
}
}
}
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 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;
}
}
}