How to exit from method back to a menu choice? - java

I've been working on a few projects recently and I can't seem to fully crack how to go from a menu option which takes you into a method, but then from that method return to the menu and prompt the user with the same options?
String userChoice = console.nextLine();
do {
switch (userChoice) {
case "1":
enteringContacts();
break;
case:"xyz"
}
}while(!userChoice.equals("xyz"));
I've used a do While loop but instead it just repeats the method? The method "EnteringContacts" is shown below:
public static void enteringContacts(){
Scanner console = new Scanner(System.in);
System.out.println("Welcome, How to use the system:");
System.out.println("Enter the contacts name, then press enter");
System.out.println("Enter the contacts number, then press enter");
String exitContactInsert = " ";
do {
contactName.add(console.nextLine());
contactNumber.add(console.nextLine());
System.out.println("Do you wish to add another?");
exitContactInsert = console.nextLine();
if (exitContactInsert.equals("no")) {
return;
} else {
System.out.println("Please enter another contact");
}
} while (exitContactInsert.equals("yes"));
}
Any help is appriciated!

Because you should ask user again for his choice every loop, before looping the "while" again.
add
userChoice = console.nextLine();
before line:
}while(!userChoice.equals("xyz"));

You should try to reorganize the code and to separate the logic from the user dialogs. You can provide an enum with possible actions:
public enum UserAction {
EDIT_CONTACT,
ADD_CONTACT,
...,
QUIT
}
And for example your logic class:
class Logic {
public void mainLoop() {
while (true) {
UserAction action = UserDialogs.getUserAction();
switch(action) {
case EDIT_CONTACT:
editContact();
break;
case ...
case QUIT: return;
}
}
}
}
And you should move a responsibility of parsing entered text in options to the dedicated class with static methods:
class UserDialogs {
public static UserAction getUserAction() {
System.out.println("Select an action (1-edit, 2-add, 3-..., Q-quit):");
Scanner scanner = new Scanner(System.in);
while (true) {
String response = scanner.nextLine().toUpperCase();
switch (response) {
case "1" : return EDIT_CONTACT;
case "2" : return ADD_CONTACT;
case ...
case "Q" : return QUIT;
default:
System.out.println("Wrong selection, try again");
}
}
}
}

If you'll be taking user response in the loop, then each iteration will be determined separately, performing different action each time until user will provide xyz.
String userChoice;
do {
userChoice = console.nextLine();
switch (userChoice) {
case "1":
enteringContacts();
break;
case:"xyz"
}
}while(!userChoice.equals("xyz"));

Related

A right way to use Scanner and Random in Switch-statement with Try/catch

I'm trying to make a text-based game in Java. and I am going to have a lot of switch-statement with scanner, but I'm not sure which way would be the best.
What would be a best way to make switch-statement with Scanner?
is try+catch better? or do loop?
and if I have, let's say, 10 switch-statement. Is it better to have 10 different Scanner declared for each switch-statements?
I like to have try+catch styled switch-statement with individual Scanner in it, but someone said that it is not necessary, and take too much wasting memory this way. I prefer to recall the method when a wrong type input was put in, and I think try+catch was better in this way because when it was recalled it also recalled Scanner and Random, giving us a chance to reset the input a User put in and also the randomly generated number by Random.
These code down here are examples.
and is the code here not a good code?
(just when it comes to the try+catch, scanner usages)
public static void levelUpAsk_111(Character chosenMember) {
try {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int dicePercent = rand.nextInt(6) + 1;
int num = sc.nextInt();
if (num == dicePercent ) {
System.out.println("** Congratulation!!");
sc.nextLine();
System.out.println("**Which one would you like to increase?");
System.out.println("1. +20 HP");
System.out.println("2. +10 MP");
System.out.println("3. +5 ATT");
levelUpAsk_222(chosenMember); //the second method
} else if (num > 7 || num < 1) {
System.out.println("Please from 1 to 6");
levelUpAsk_111(chosenMember); //recall itself
} else {
System.out.println("** Sorry..");
sc.nextLine();
}
} catch (InputMismatchException e) {
System.out.println("Please integer only");
levelUpAsk_111(chosenMember); //recall itself
}
}
public static void levelUpAsk_222(Character chosenMember) {
try {
Scanner sc = new Scanner(System.in);
int select = sc.nextInt();
switch (select) {
case 1:
System.out.println("** HP has increased by 20.");
break;
case 2:
System.out.println("** MP has increased by 10.");
break;
case 3:
System.out.println("** ATT has incrased by 5.");
break;
default:
System.out.println("From 1 to 3");
levelUpAsk_222(chosenMember); //recall itself
break;
}
} catch (InputMismatchException e) {
System.out.println("Only integer please"); //recall itself
levelUpAsk_222(chosenMember);
}
}
For switch statements, you do not need to create a new Scanner object each time you want to use it. You can declare it once at the beginning of each method. It is more confusing if you have to deal with multiple Scanner objects in your code than if you only have one.
You can create use a switch looping menu with a default: to catch the unlisted inputs. For example
switch (option){ //assuming you declared option to an int and user has inputted a value for it
case 1:
{
//put some code here
break;
}
case 2:
{
//put more code here
break;
}
case 0:
{
//used to exit the loop
break;
}
default:
{
System.out.println("Please enter a integer only");
levelUpAsk_111(chosenMember); //you can do it this way, or use a do-while looped switch menu that keeps asking until a valid int is input
}
}

difficulty displaying items in to-do list

I'm trying to build a text based to do list in Java but I'm having some difficulties when it comes to displaying the items.
When I run the code and enter "1" the contents of the to do list are displayed back to me, but they keep looping and they never stop. I'm assuming this has something to do with the while loop that checks the userChoice variable but my question is why does the list keep reiterating even after the break statement? What I'd like to have happen is to enter a number, have the action performed, and then have the instruction prompt displayed again.
java code:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
// create an arraylist to store users items
static ArrayList<String> toDoList = new ArrayList<String>(3);
public static void main(String[] args) {
// greet the user
System.out.println("**Your To-Do list** \n");
// add default items to list
toDoList.add("Buy Groceries");
toDoList.add("Work Out");
toDoList.add("Play CS");
// user menu/instruction
System.out.println("Please select from one of the following options: \n 1. Show to-do list \n 2. Add item " +
"\n 3. Remove item \n 4. Exit program \n");
// prompt user for their choice
System.out.print("Enter your choice: ");
// get user choice
Scanner input = new Scanner(System.in);
int userChoice = input.nextInt();
while (userChoice != 4) {
switch (userChoice) {
case 1:
getToDoList();
break;
case 2:
// create method that allows you to add item to the toDolist
break;
case 3:
// create method that allows you to remove item from the toDolist
break;
case 4:
// create method that terminates application
break;
}
}
}
// method that returns contents of the list
public static void getToDoList(){
for (int i = 0; i < toDoList.size(); i++) {
System.out.println(toDoList.get(i));
}
}
}
It is because you did not request to read from user again.
case 1:
getToDoList();
input.nextInt();
break;
Or move the input.nextInt(); outside of switch block (below it).
Because userChoice is always 1, so it always loop.
import java.util.ArrayList;
import java.util.Scanner;
public class Groceries {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> a=new ArrayList<String>();
a.add("Food");
a.add("Furniture");
a.add("Plywood");
while(true)
{
System.out.println("Enter your choice");
System.out.println("Your choice List\n 1:getList 2.addinthelist 3.removefromlist 4.exit");
Scanner sc=new Scanner(System.in);
int a1=sc.nextInt();
switch(a1)
{
case 1:
System.out.println(a);
break;
case 2:
System.out.println("List before addition of elemnt is :"+a);
System.out.println("Enter element to be added into the string");
String sss=sc.next();
a.add(sss);
System.out.println("List after addition of element is :"+a);
break;
case 3:
System.out.println("List before deletion of elemnt is "+a);
System.out.println("Enter an index of an element to be removed");
int abc=sc.nextInt();
a.remove(abc);
System.out.println("List after Deletion of an element is "+a);
break;
case 4:
System.exit(0);
default:
System.out.println("You entered wrong number !! Please enter 4 to exit");
}
}
}
}

Scanner using with while loop and switch statement

I'm creating a simple console app in Java and I have a trouble. This is my code:
boolean isActive = true;
Scanner scanner = new Scanner(System.in);
do {
try {
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("Search By Registration number: " +
"\n------------------------------");
System.out.println("Enter registration number!");
String regNumber = scanner.nextLine();
if (regNumber == incorrect) {
continue; // return to case 1 and ask enter regnumber one more time
} else {
// do stuff
}
break;
case 2:
System.out.println("Exit the search option: ");
isActive = false;
break;
default:
System.out.println("Your selection was wrong. Try one more time!");
break;
}
} catch (InputMismatchException ex) {
System.out.println("Your selection was wrong. Try one more time!");
}
scanner.nextLine();
} while (isActive);
And I can't to return to case 1 if an error occured. So, if error occured, the user must get the message About entering the registration number one more time and so on.
You need to use equals() when you check a regNumber
if (regNumber.equals(incorrect)) {
System.out.println("Incorrect!");
continue;
} else {
System.out.println("Correct!");
}
But even then, your program doesn't work properly, change String regNumber = scanner.nextLine() on this:
String regNumber = scanner.next();
You could put a loop around your input for the regNumber, in order to listen for input while it's not correct.
String regNumber = incorrect;
// String is a reference type, therefore equality with another String's value
// must be checked with the equals() method
while(regNumber.equals(incorrect)){
if (regNumber.equals(correct)) {
// Do something if input is correct
}
}
This may be not the exact solution you wanted, but think of the same concept and apply it to your program. Also see this for more information about String comparison. Hope this helped!

java try and catch..infinite loop

I am having a problem with try and catch. My program is to insert three different strings name, address and phone number then I convert these three in to a single String using toString method.
I have problem with exception handling whenever I write a wrong choice (String or other data type) then catch works infinity times.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<String> arraylist= new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format="Empty";
int x=1;
int flag=0;
do
{
try
{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice=input.nextInt();
switch (choice)
{
case 1:
{
System.out.println("Enter name ");
name=input.next();
System.out.println("Enter phone number");
phoneNumber=input.next();
System.out.println("Enter address");
address=input.next();
format=FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;
case 2:
{
System.out.println("Name Phone number Address");
System.out.println();
for(int i=0;i<flag;i++)
{
System.out.println(arraylist.get(i));
}
}
break;
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");`
}while(x==1);
}
}
//The format class ...//returns format for string
Your try and catch are not related to a loop, nor to your problem.
while(x==1)
is what you test on, yet you never change the value of x, so it will always remain 1, and thus the above check will always return true.
I think I now know what your problem actually is.
Simply adding input.nextLine() at the very beginning at your code will stop the input running havoc.
boolean wrongInput = false;
do {
try {
if (wrongInput) {
input.nextLine();
wrongInput = false;
}
System.out.println("Enter your choice");
[...]
} catch (...) {
wrongInput = true;
}
should do the trick. However, please note that I noticed two errors in your program (which might be because I do not have the CreateFormat class of yours), (a) I cannot add a number to the address and (b) there is no option to stop the loop (which I strongly recommend - where you simply set x = -1 or something similar, better use a boolean to end the loop though).

What is my error in using a String in the case method

I am trying to use the Scanner to hold aString for the variable "how", and if "how" = yes then execute. the 'yes' case and if 'no' execute the 'no' case this is all inside the else statement from the first question
package test;
import java.util.Scanner;
public class Try {
public static void main(String[] args) {
System.out.println("hello world");
Scanner input = new Scanner(System.in);
System.out.println("Do you wanna make android apps");
System.out.println("Yes or no ?");
String copy=input.nextLine();
System.out.println(copy);
if(copy.equals("yes")) {
System.out.println("you should continue java");
} else {
System.out.println("Do you wanna make iso apps");
System.out.println("yes or no");
String how = null;
switch(how.toLowerCase()){
case "yes" :
System.out.println("test worked");
break;
case "no":
System.out.println("test worked 2");
break;
}
}
}
}
String how = null;
switch(how.toLowerCase()) //here you are trying to convert null value
The above statement is trying to convert null value to lowercase.
Assign the value to
String how = input.nextLine();
Hope this solves your issue..
Change String how = null; to String how = input.nextLine();
package test;
import java.util.Scanner;
public class Try {
private enum how_string { yes,no};
public static void main(String[] args) {
System.out.println("hello world");
Scanner input = new Scanner(System.in);
System.out.println("Do you wanna make android apps");
System.out.println("Yes or no ?");
String copy=input.nextLine();
System.out.println(copy);
if(copy.equals("yes")){
System.out.println("you should continue java");
}else{
System.out.println("Do you wanna make iso apps");
System.out.println("yes or no");
String how=input.nextLine();
how_string p = how_string.valueOf(how.toLowerCase());
switch(p){
case yes :System.out.println("test worked");
break;
case no :System.out.println("test worked 2");
break;
}
}
}}
Just like your String copy=input.nextLine();
You need to change String how = null; to String how = input.nextLine();
And for your first if else, you better change
copy.equals("yes")
to
copy.equalsIgnoreCase("yes")

Categories

Resources