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;
}
}
}
}
Related
I have created a class that has methods for getting, setting and displaying computer details. I have then created a test class that displays this methods and uses a textual menu for the user to interact with (shown below). I now need to upgrade this to a GUI interface using JOptionPane but I have no clue where to start as this is all new to me. If anyone has any advice or suggestions it would be greatly appreciated.
import java.util.Scanner;
public class SystemTest_Y3881268 {
public static void main(String[] args) {
//Create System_Y3881268 object and test methods
System_Y3881268 s=new System_Y3881268("Lenovo",
"Ideacentre A340-24IWL", 2);
s.setHardDisk(2);
s.setMemory(128);
s.setPurchaseCost(599);
//Create textual menu
int memorySize;
double hardDiskSize;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
char choice;
do
{
System.out.println();
System.out.println("***** Computer system menu *****");
System.out.println();
System.out.println("Choice 1: Print System Details");
System.out.println("Choice 2: Diagnose System");
System.out.println("Choice 3: Set Details");
System.out.println("Choice 4: Print System Properties");
System.out.println("Choice 5: Quit the Program");
System.out.println();
System.out.println("Enter a number from 1 - 5");
System.out.println();
choice = keyboard.next().charAt(0);
switch(choice)
{
case '1':
{
s.displayDetails();
}
break;
case '2':
{
s.diagnoseSystem();
}
break;
case '3':
{
System.out.println("Enter hard disk size in GB: ");
hardDiskSize = keyboard.nextDouble();
if(hardDiskSize<2)
{
System.out.println("Hard disk size = Low");
}
else
{
System.out.println("Hard disk size = Ok");
}
System.out.println();
System.out.println("Enter memory size in MB: ");
memorySize = keyboard.nextInt();
if(memorySize<128)
{
System.out.println("Memory Ok = False");
}
else
{
System.out.println("Memory Ok = True");
}
}
break;
case '4' :
{
System_Y3881268.displaySystemProperties();
}
break;
case '5' : break;
default : System.out.println("Enter only numbers from 1 - 5");
System.out.println();
}
} while(choice != '5');
}
}
If you want to have more flexibility than a JOptionPane I'd suggest you use the JDialog class. You can add components in the constructor of your dialog like JTextbox, JLabel, JButton and many more.
First, Create yourself a class that extends JDialog.
public class Whatever extends JDialog
{
public Whatever(Frame ownerFrame)
{
super(ownerFrame, "Title", true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.rootPane.setBorder(new LineBorder(new Color(125, 0, 0), 3, true));
}
}
Then in your main class your gonna call it like that :
Whatever whatev = new Whatever(myFrame);
whatev.setSize(800, 600);
whatev.setVisible(true);
For more info on the JDialog class : https://docs.oracle.com/javase/7/docs/api/javax/swing/JDialog.html
You can use this line of code:
JOptionPane.showMessageDialog(f,"Message", "Title", JOptionPane.WARNING_MESSAGE);
where f is the parent JFrame, it can be null,
JOptionPane.WARNING_MESSAGE is the type of the dialog.
For more information, refere to https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
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
the following code terminate after try catch block catches exception.its not allowing me to make choice from the menu option. so my question is what changes do i have to make on this code so that i can loop back so that i can get user input again.
public class Main {
public static void main(String[] args) {
Modify modifyObj = new Modify();
int choice = 0 ;
Scanner input = new Scanner(System.in);
//begin loop
do {
try{
//display menu
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
choice = input.nextInt(); //gets user input
switch (choice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}// end of switch statement
break;
}//end oftry
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
continue;
}
}while (choice!=0); //loop until user exit 0.
}//end of main
}// end of Main class
Make sure choice isn't 0 before you continue;
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
choice = 1; // <-- not 0.
continue;
}
Note that you default choice to an initial value of 0.
You Could Use Methods
If you extracted your logic into one (or two) utility methods to display the menu and get the user's choice it would simplify things; something like
private static void showMenu() {
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
}
private static int getUserOption(Scanner input) {
while (true) {
showMenu();
if (input.hasNextInt()) {
int t = input.nextInt();
switch(t) {
case 0: case 1: case 2: case 3:
return t;
}
} else {
input.nextLine();
}
}
}
Then your main could invoke it like
public static void main(String[] args) {
Modify modifyObj = new Modify();
Scanner input = new Scanner(System.in);
int choice;
// begin loop
do {
choice = getUserOption(input);
if (choice != 0) {
System.out.printf("You chose %d.%n", choice);
}
} while (choice != 0); // loop until user enters 0.
}// end of main
My program compiles, but I am getting run time exceptions, not sure if I need to handle them? methods commented out and for extended class, they just display text. I also don't know if I am using labels correctly? I want my program to loop and handle exceptions for erroneous characters, which it does, but it should only terminate if the user enters "5".
import java.util.*;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Mainmenu3 {
// extends premierLeagueClubs
public static void main(String args[]){
boolean shouldExit = false;
int option = 0;
loop: while (!shouldExit) {
try{
Scanner in = new Scanner(System.in);
menu();
System.out.println("\n");
option = in.nextInt();
} // end try
catch(InputMismatchException e) {
String option2 = Integer.toString(option);
} // end catch
switch (option) {
case 1:
chooseTeam();
break;
case 2:
createProfile();
break;
case 3:
loadSave();
break;
case 4:
credits();
break;
case 5:
break loop;
default:
System.out.println("Invalid choice");
}
} // end switch
} // end main method
public static void chooseTeam(){
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Select Team : ");
System.out.println("1. Arsenal");
System.out.println("2. Aston Villa");
System.out.println("3. Bournemouth");
System.out.println("4. Chelsea");
System.out.println("5. Crystal Palace");
System.out.println("6. Everton");
System.out.println("7. Leicester City");
System.out.println("8. Liverpool");
System.out.println("9. Manchester United");
System.out.println("10. Manchester City");
System.out.println("11. Newcastle United");
System.out.println("12. Norwich City");
System.out.println("13. Southampton");
System.out.println("14. Stoke City");
System.out.println("15. Sunderland");
System.out.println("16. Swansea City");
System.out.println("17. Tottenham Hotspur");
System.out.println("18. Watford");
System.out.println("19. West Brom");
System.out.println("20. West Ham United");
int option = 0;
Scanner in = new Scanner(System.in);
//menu();
System.out.println("\n");
option = in.nextInt();
System.out.println("You entered : " + option);
} // end chooseTeam
public static void createProfile(){
} // end createProfile
public static void loadSave(){
} // end loadSave
public static void credits(){
} // end credits
public static void menu(){
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Created by Darren Estcourt");
System.out.println("\n");
System.out.println("Please choose an option : ");
System.out.println("\n");
System.out.println("1. Choose team");
System.out.println("\n");
System.out.println("2. Create profile");
System.out.println("\n");
System.out.println("3. Load/Save game");
System.out.println("\n");
System.out.println("4. Credits");
System.out.println("\n");
System.out.println("5. Quit");
System.out.println("\n");
String option="0";
Scanner in = new Scanner(System.in);
System.out.println("\n");
option = in.nextLine();
switch (option) {
case "1":
chooseTeam();
break;
case "2":
createProfile();
break;
case "3":
loadSave();
break;
case "4":
credits();
break;
case "5":
System.out.println("Goodbye!");
default:
System.out.println("Please select an option between 1 and 4");
//menu();
} // end switch
} // end menu
} // end class
There are multiple issues with your program:
you define shouldExit but nowhere do you update it according to user input
you scan and process user input both in main() and in menu(). generally, your code isn't structured in a coherent readable manner and there is little reuse.
println() already prints a new line (as opposed to print())
for the love of programming goddess - do not use System.exit() to terminate a Java program
here is an example of a working class with the above guidelines implemented to a pasable degree :
import java.util.*;
public class Mainmenu3
{
static Scanner in;
public static void main(String args[])
{
in = new Scanner(System.in);
boolean shouldExit = false;
while (!shouldExit) {
displayMenu();
shouldExit = processUserInput();
}
}
public static void displayMenu()
{
System.out.println();
System.out.println("Created by Darren Estcourt");
System.out.println("Please choose an option : ");
System.out.println("1. Choose team");
System.out.println("2. Create profile");
System.out.println("3. Load/Save game");
System.out.println("4. Credits");
System.out.println("5. Quit");
}
public static int getUserInput()
{
int option = -1;
try {
option = in.nextInt();
} catch (InputMismatchException e) {
// When a scanner throws an InputMismatchException,
// the scanner will not pass the token that caused the exception,
// so that it may be retrieved or skipped via some other method.
in.next();
} catch (NoSuchElementException e) {
// input is exhausted
option = 5;
} catch (IllegalStateException e) {}
// scanner is closed
option = 5;
}
return option;
}
public static boolean processUserInput()
{
int option = getUserInput();
switch (option) {
case 1:
chooseTeam();
break;
case 2:
createProfile();
break;
case 3:
loadSave();
break;
case 4:
credits();
break;
case 5:
System.out.println("Goodbye!");
return true;
default:
System.out.println("Invalid choice");
}
return false;
}
public static void chooseTeam()
{
System.out.println();
System.out.println("Select Team : ");
System.out.println("1. Arsenal");
System.out.println("2. Aston Villa");
System.out.println("3. Bournemouth");
System.out.println("4. Chelsea");
System.out.println("5. Crystal Palace");
System.out.println("6. Everton");
System.out.println("7. Leicester City");
System.out.println("8. Liverpool");
System.out.println("9. Manchester United");
System.out.println("10. Manchester City");
System.out.println("11. Newcastle United");
System.out.println("12. Norwich City");
System.out.println("13. Southampton");
System.out.println("14. Stoke City");
System.out.println("15. Sunderland");
System.out.println("16. Swansea City");
System.out.println("17. Tottenham Hotspur");
System.out.println("18. Watford");
System.out.println("19. West Brom");
System.out.println("20. West Ham United");
int option = getUserInput();
System.out.println("You entered : " + option);
} // end chooseTeam
public static void createProfile()
{
System.out.println("createProfile");
}
public static void loadSave()
{
System.out.println("loadSave");
}
public static void credits()
{
System.out.println("credits");
}
}
I'm trying to make a simple Menu with the switch statement. However i'm having a problem with the switch:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException{
char selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char)System.in.read();
switch(selection){
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
}
}
while(selection != '3');
}
}
For some reason, when selecting either one or two, the result is that print menu gets printed twice, like this:
Program output:
Choose option:
1. opt1.
2. opt2.
3. opt3.
1
opt1 chosen
Choose option:
1. opt1.
2. opt2.
3. opt3.
Choose option:
1. opt1.
2. opt2.
3. opt3.
The question is, what causes this problem?
When you press a number and <Enter> this is two characters not one. i.e. you are typing
1\n
This is unavoidable, but you can chose to parse the input differently with Scanner which handles this differently, or you can ignore it. (or you can expect the user must type a \n after a number...
As Peter pointed out, the problem arises because of the way you are reading the 'selection' input. You can correct the functionality as follows:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException {
char selection = '0';
while (selection != '3') {
if (selection != '\n') {
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
}
selection = (char) System.in.read();
switch (selection) {
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
default:
break;
}
}
}
}
Peter Lawrey is right
I'm suggest using Scanner class :
public static void printMenu() throws IOException {
Scanner scanner = new Scanner(System.in);
int selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char) scanner.nextInt();
switch(selection){
case 1:
System.out.printf("opt1 chosen\n");
break;
case 2:
System.out.printf("opt2 chosen\n");
break;
case 3:
break;
}
scanner.nextLine();
}
while(selection != '3');
}