I am new to Java as well as to enum types.
I am trying to make a menu selection that uses enum types as its valid choices and that displays the following integer selections for the user:
Welcome to Frank's Banking Application.
Enter:
1. Create Bank
2. Add a branch to a Bank
3. Add a customer to a Branch
4. Make a transaction with a customer
5. Display Banks, Branches, Customers, and Transactions.
6. Quit Application.
Selection ->
However, the problem I am faced with is that enum constants do not seem to accept integer values as their names. So I am stuck making them letters for now. This is the code I have so far:
import java.util.Scanner;
enum MenuOptions
{
z("Continue"), a("Create Bank"), b("Add Branch"), c("Add Customer"),
d("Make Transaction"), e("Display Information"), q("Quit");
// field
private String meaning;
// constructor
MenuOptions(String meaning)
{
this.meaning = meaning;
}
// getters
public String getMeaning()
{
return meaning;
}
}
public class Main
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Welcome to Frank's Banking Application.");
MenuOptions menuOptions = MenuOptions.z;
while (menuOptions != MenuOptions.q)
try
{
menu();
menuOptions = MenuOptions.valueOf(input.nextLine());
switch (menuOptions)
{
case a:
//createBank();
break;
case b:
//addBranch();
break;
case c:
// addCustomer();
break;
case d:
// makeTransaction();
break;
case e:
break;
case q:
System.out.println("Goodbye.");
break;
default:
System.out.println("Selection out of range. Try again");
}
}
catch (IllegalArgumentException e)
{
System.out.println("Selection out of range. Try again:");
}
}
public static void menu()
{
System.out.println("\nEnter:");
System.out.println("\ta. Create Bank");
System.out.println("\tb. Add a branch to a Bank");
System.out.println("\tc. Add a customer to a Branch");
System.out.println("\td. Make a transaction with a customer");
System.out.println("\te. Display Banks, Branches, Customers, and Transactions.");
System.out.println("\tq. Quit Application.");
System.out.print("\nSelection -> ");
}
}
As can be seen, I had to edit all the enums to have letters as their name in order to allow the user input from the scanner to match their type by using the valueOf method.
Is there a way however, to allow options: 1, 2, 3, 4, 5, 6 from user input from keyboard to be taken as a restricted enum type?
Hope that makes sense and thanks.
You can use e.g.:
MenuOptions.values()[1]
To get the second enum, numbering starts at 0.
values() is an array of all given enum values.
In your case it would be like:
MenuOptions.values()[Interger.parseInt(input.nextLine().trim()) - 1]
Related
This question already has answers here:
Java to sort list of custom object on the basis of string
(7 answers)
Closed 2 years ago.
I wrote a working method to insert objects into arrayLists in my SortedArrayList class. The problem is, it sorts by the first letter of the first element of the ArrayList.
I would like to be able to choose how the ArrayList is sorted (e.g. by first letter of the surName or by the number of books in a user object. How do I approach this?
An example of the type of object stored: User(String firstName, String surName, int books)
import java.io.*;
import java.util.Scanner;
public class Driver {
//These SortedArrayLists have been derived from the sorted arraylist class
public static SortedArrayList<User> sortedUsers = new SortedArrayList<>();
public static SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
//This static method checks that input matches records and then sets the loaning user information
//for the book to be loaned while incrementing the number of books held by the user.
public static void loanBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)) {
b.setLoanStatus(true);
b.setLoaningUser(user);
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1); //The number of books of a given object is found then incremented by one to create the new value, which is set
break;
}
}
}
//This static method checks that input matches records and clears loaning user information
//for the book to be loaned while lowering the number of books held by the user by 1.
public static void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.setLoanStatus(false);
b.setLoaningUser(null);
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
//The number of books for the object instance of a user in question is decreased since they have returned a book and thus have one less book.
}
}
}
//This is the main method from which the program starts.
public static void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
}
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
//This toString replace method removes unwanted items for a cleaner print of book object information and removes the string description for user's name described in the user toString method.
System.out.println(sortedBooks.toString().replace("[","").replace("]","").replace("Name: ", ""));
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers.toString().replace("[","").replace("]",""));
break;
case 'i':
System.out.println("Enter the loaning out data. ");
User user = readNames();
Book book = readBookName();
//A book object is created based on user input, then an attempt at altering the
// relevant object information is made via the loanBook method.
loanBook(book, user);
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
User userReturn = readNames();
Book bookReturn = readBookName();
//User input is used to create user and book objects so that a book can be returned
//by use of the returnBook method, resetting any user information about the book and decreasing the count for number of booksheld by the user.
returnBook(bookReturn, userReturn);
break;
default: //this case occurs if input does not match any of the switch statement cases.
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
The sortedArrayList class:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//This insert method ensures that an object added to an arraylist is added in a sorted order.
public void insert(E value) {
if (this.size() == 0){
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i) );
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0){
return; }
}
this.add(value);
}
You could simply use a regular ArrayList (or any kind of built in List) and, after you've added all elements, use Collections.sort().
Here you can guve your list as first parameter and a custom Comparator as a second. For the custom comparator you can provide your desired comparison (surname etc.).
This sort is also more efficient than what you are currently using.
Here is the JavaDoc: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)
I have defined an enum in java to use that for validating user input. I am having an issue where if the user puts in something the program just exits and doesn't loop that way I'm expecting it to.
I want to be able to loop until the user has inputted one of the items on the list.
Here's the code in question:
// import System.out
import static java.lang.System.out;
// import scanner for user-input
import java.util.Scanner;
public class AnimalTest {
// enum for user-input
enum animal{
COW,
DUCK,
PIG,
SHEEP
}
public static void main(String[] args){
// create scanner for user input
Scanner userInput = new Scanner(System.in);
do {
// print out menu
out.println("Which animal are you?\nCow\nDuck\nPig\nSheep");
// get user-input and validate against enum
try{
animal selection = animal.valueOf(userInput.nextLine().toUpperCase());
}
catch (Exception e){
out.println("Please type in one of the animals above.");
}
finally{
break;
}
}
while (true);
// switch based on validated user input
switch(selection){
case COW:
cow cow0 = new cow();
cow0.sound();
break;
case DUCK:
duck duck0 = new duck();
duck0.sound();
break;
case PIG:
pig pig0 = new pig();
pig0.sound();
break;
case SHEEP:
sheep sheep0 = new sheep();
sheep0.sound();
break;
}// end switch
}// end main
}// end class
After this, I am going to use a switch and one of the errors the compiler is throwing at me is that the variable selection is not defined so I can use the switch on it, any insight on this aspect as well is apprciated
Aside from the problem highlighted by #mauvecrow's answer, your do/while is useless. a finally block ALWAYS runs, so your while loop will always break at the end. You might as well delete the break, and the entire 'while' construct. Perhaps you intended to loop until a correct answer is entered? Then put the break after the selection = line, within the try block.
I believe your issue is that your "animal selection" variable is defined locally in the try block, thus it is out of scope by the time you get to the switch case.
I have this code (with minor changes for things to run for me) and it works. I declared and initialized (even initialization to null is fine) first.
import static java.lang.System.out;
//import scanner for user-input
import java.util.Scanner;
public class AnimalTest {
// enum for user-input
enum Animal{
COW,
DUCK,
PIG,
SHEEP
}
public static void main(String[] args){
// create scanner for user input
Scanner userInput = new Scanner(System.in);
Animal selection = null;
do {
// print out menu
out.println("Which animal are you?\nCow\nDuck\nPig\nSheep");
// get user-input and validate against enum
try{
selection = Animal.valueOf(userInput.nextLine().toUpperCase());
}
catch (Exception e){
out.println("Please type in one of the animals above.");
}
finally{
break;
}
}
while (true);
// switch based on validated user input
switch(selection){
case COW:
out.println("cow");
break;
case DUCK:
out.println("duck");
break;
case PIG:
out.println("pig");
break;
case SHEEP:
out.println("sheep");
break;
default: out.println("not the expected animal");
}// end switch
}// end main
}// end class
I'm trying to write a program that lets the user create 2 depots.
I have it in a switch statement, but when it completes and I go back to create the second depot it overwrites depot1.
I'm not sure how I'd go about creating 2 separate depots.
do {
System.out.println("(1) Add depot number 1 ");
System.out.println("(2) Remove a depot");
System.out.println("(3) Exit program");
option = console.nextInt();
switch (option) {
case 1:
depot1 = new Depot();
if (depot1.checkDepot() == true){
System.out.println("Enter Depots name");
n = console.next();
depot1.setDepotName(n);
}
else{
System.out.println("Error only 2 depots allowed");
}
break;
case 2:
case 3:
System.exit(0);
}
}
while (option !=3);
public class Depot
{
private String name;
private Product product1, product2, product3;
static int depotCounter = 0;
// Constructor to count depot objects
public Depot(){
depotCounter++;
}
// Method to make sure no more than 2 depots are created
public boolean checkDepot(){
if (depotCounter <= 2){
return true;
}
else{
return false;
}
Is my depot class, I have a counter and a checkdepot to make sure only 2 get created.
It creates depot1 fine, but when I go into the statement again and click (1) it re-writes a new name over the object depot1
When you enter option 1, all it does is execute the code in the first "switch-case". And in there, you always use depot1 as variable. By the way, after you exit the switch statement, your depot gets lost anyways, because you declare it in that block. What you could do, is something like this:
do {
Depot depot1;
Depot depot2;
//Your code for the menu, e.g. selecting what the user wants to do
switch (option) {
case 1 :
if (depot1 == null) {
depot1 = new Depot()
//Do what you want to do with your depot
} else if (depot2 == null) {
depot2 = new Depot()
//Same as above
}
break;
//Rest of the switch statement
}
} while (option != 3)
What I did there, is just use 2 different variables for the depots, and when you want to create a new depot, you first check if you already created a depot (if e.g. depot1 points at some object, so if depot1 == null is false) and then create the corresponding depot. If you haven't created a depot at all, then depot1 IS null, so you create depot1. If you already created depot1, depot1 == null is false, so it jumps to the second if-block, checks if depot2 is null, it is, so it creates depot2. When there already are 2 depots, it does nothing.
If you want more than 2 depots, what Backpack says in his answer is your way to go.
To summarize:
a) You need different variables for your depots, not only one, so you don't just overwrite your current depot.
b) If you want your objects to persist outside of the switch statement, you need to declare them outside of it. Variables only "live" inside the block, that you declare them in.
You could try creating a list of depots and just iterate through them. That way you can add an object whenever you please to the list, or delete it from the list.
Also, you can add an identifier in the depot object, that gives like an ID or something so you can differentiate them.
int option = 0;
Depot depot;
String name;
Scanner console = new Scanner(System.in);
List<Depot> depotList = new ArrayList<>();
do {
System.out.println("(1) Add depot number ");
System.out.println("(2) Remove a depot");
System.out.println("(3) Exit program");
if (console.hasNextInt()) {
option = console.nextInt();
switch (option) {
case 1:
if (depotList.size() < 2) {
System.out.println("Enter new Depot name:");
if (console.hasNext()) {
name = console.next();
depot = new Depot();
depot.setDepotName(name);
depotList.add(depot);
}
} else {
System.out.println("Error only 2 depots allowed");
}
break;
case 2:
// remove depot code
break;
case 3:
break;
}
}
} while (option != 3);
System.out.println("Depots added:");
System.out.println("-------------");
depotList.forEach(currentDepot ->
System.out.println(currentDepot.getDepotName()));
To do this I am using a lot of nested if/else statements.
I have three main branches (living animal, living plant, non-living thing) and each of these have multiple branches. Making it something like 60 different decisions.
I am having a lot of trouble getting it to cooperate, and control all the if/else statements. I don't have much code for it yet because of having to restart so much but currently I am at:
System.out.println("Think of Something");
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
if (user.equals("living animal")); {
//starts animal tree
System.out.println("Does it have feathers, fur, or neither?");
String user2 = get.nextLine();
if (user2.equals("feathers")); {
System.out.println("is it bigger than a soccer ball?");
}
} else if (user2.equals("fur")); {
System.out.println("is it domesticated?");
// end animal tree
} else if (user.equals("living plant")); {
// start plant tree
System.out.println("is it a tree?");
}
} // end method
} //end program
You are writing out your if statements with this syntax:
if (user2.equals("feathers"));
{
System.out.println("is it bigger than a soccer ball?");
}
However, the body of the if block will always execute because you have a semicolon that finishes the statement prematurely:
if (user2.equals("feathers")); // <-- The semicolon here finishes the if statement, which means the if statement does nothing
{
System.out.println("is it bigger than a soccer ball?"); // <-- This line is ran no matter what the if statement was
}
Basically all you have to do to get the if or else if statements to work correctly is to remove the unwanted semicolons.
As an example for how to a aproach a problem that gets to complex to cope with. It is not ment to be an ready to use program to run out of the box.
Its ment to answer the question how to simplify things when "having a lot of trouble getting it to cooperate, and control all the if/else statements." A strategy for such cases if you want.
Also I overdid things a little for demonstration. In practice, you do what seems convenient. Also: I made everything static for simplicity - in a grown application you surely would use instances instead.
Step 1: You start with a very simple class frame. Simplicity is key. Don't put to much in it. Just sketch what you know you want it to do:
public class TwentyQuestions{
static void mainQuestioning(){
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
switch(user){
case "living animal" :
askLivingAnimalQuestions();
break;
case "living plant":
askLivingPlantQuestions();
break;
case "non-living":
askNoneLivingQuestions();
break;
default:
handleWrongInput();
}
}
}
Sure, that thing above won't compile as the details are not implemented by now(some methods are missing) - But note how the problem has simplified a lot(no nested if's) and most probably you can imidiately see what it is supposed to do. Keeping it simple, straight forward is key.
Step 2: Now you can easily create the methods you sketched so far. Lets do that:
public class TwentyQuestions{
static void handleWrongInput(){
System.err.println("I am no longer playing with you as you don't answer my question properly");
System.exit(1);
}
static void askLivingAnimalQuestions(){
System.out.println("Does it have feathers, fur, or neither?");
String user = get.nextLine();
switch(user){
case "feathers":
askLivinAnimalWithFeathersQuestions();
break;
case "fur":
askLivinAnimalWithFurQuestions();
break;
default:
handleWrongInput();
}
}
static void askLivingPlantQuestions(){
System.out.println("is it a tree?");
String user = get.nextLine();
if("yes".equals(user)){
System.out.println("So its a tree!");
return;
}
}
static void askNoneLivingQuestions(){
System.out.println("WhateverNoneLivingQuestion ?");
String user = get.nextLine();
switch(user){
//add possible responses here.
default:
handleWrongInput();
}
}
static void mainQuestioning(){
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
switch(user){
case "living animal" :
askLivingAnimalQuestions();
break;
case "living plant":
askLivingPlantQuestions();
break;
case "non-living":
askNoneLivingQuestions();
break;
default:
handleWrongInput();
}
}
}
Now I broke the problem down even more. But it still/again won't compile because methods are missing for animals with fur and animals with feathers.
Step 3: Implement them as well:
public class TwentyQuestions{
static void handleWrongInput(){
System.err.println("I am no longer playing with you if you don't answer my question properly");
System.exit(1);
}
static void askLivinAnimalWithFeathersQuestions(){
System.out.println("is it bigger than a soccer ball?");
String user = get.nextLine();
//don't know how you want to continue;
//....
}
static void askLivinAnimalWithFurQuestions(){
System.out.println("is it domesticated?");
String user = get.nextLine();
//don't know how you want to continue;
//....
}
static void askLivingAnimalQuestions(){
System.out.println("Does it have feathers, fur, or neither?");
String user = get.nextLine();
switch(user){
case "feathers":
askLivinAnimalWithFeathersQuestions();
break;
case "fur":
askLivinAnimalWithFurQuestions();
break;
default:
handleWrongInput();
}
}
static void askLivingPlantQuestions(){
System.out.println("is it a tree?");
String user = get.nextLine();
if("yes".equals(user)){
System.out.println("So its a tree!");
return;
}
}
static void askNoneLivingQuestions(){
System.out.println("WhateverNoneLivingQuestion ?");
String user = get.nextLine();
switch(user){
//add possible responses here.
default:
handleWrongInput();
}
}
static void mainQuestioning(){
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
switch(user){
case "living animal" :
askLivingAnimalQuestions();
break;
case "living plant":
askLivingPlantQuestions();
break;
case "non-living":
askNoneLivingQuestions();
break;
default:
handleWrongInput();
}
}
}
Note how all your nested if/else that caused you trouble disapeared.
finish: Now if you additionally implement the missing questioning and add a Scanner "get" that is initialized in a main(String[] args) you should be there. It should be easy now.
Well.. That probably gives you a lot of methods for 20 nested questions: This is due to the numers of posibilities you have. You have to handle that many cases of questions and answers. No way arround it.
Better having them cleanly in their own dedicated, place than stray around somewhere(you tidy up and put everything at its place - the amount of cases/questions you have to handle stays the same).
However in a grown application you may put all your questions and answers in a datastructure like a tree. With that you could avoid the massive amount of methods and have some generalized methods instead that just walk the tree....
[ Also you can just create interim methods that do nothing ("stubs" ) for things you need but have not implemented yet to make it compile while you still developing. ]
Here is the example as a full class, which compiles and does the questioning so far as implemented:
import java.util.Scanner;
/**
*
* #author Kai
*/
public class TwentyQuestions {
static Scanner get = new Scanner(System.in);
static void handleWrongInput() {
System.err.println("I am no longer playing with you if you don't answer my question properly");
System.exit(1);
}
static void askLivinAnimalWithFeathersQuestions() {
System.out.println("is it bigger than a soccer ball?");
String user = get.nextLine();
//don't know how you want to continue;
//....
}
static void askLivinAnimalWithFurQuestions() {
System.out.println("is it domesticated?");
String user = get.nextLine();
//don't know how you want to continue;
//....
}
static void askLivingAnimalQuestions() {
System.out.println("Does it have feathers, fur, or neither?");
String user = get.nextLine();
switch (user) {
case "feathers":
askLivinAnimalWithFeathersQuestions();
break;
case "fur":
askLivinAnimalWithFurQuestions();
break;
default:
handleWrongInput();
}
}
static void askLivingPlantQuestions() {
System.out.println("is it a tree?");
String user = get.nextLine();
if ("yes".equals(user)) {
System.out.println("So its a tree!");
return;
}
}
static void askNoneLivingQuestions() {
System.out.println("WhateverNoneLivingQuestion ?");
String user = get.nextLine();
switch (user) {
//add possible responses here.
default:
handleWrongInput();
}
}
static void mainQuestioning() {
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
switch (user) {
case "living animal":
askLivingAnimalQuestions();
break;
case "living plant":
askLivingPlantQuestions();
break;
case "non-living":
askNoneLivingQuestions();
break;
default:
handleWrongInput();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
mainQuestioning();
}
}
example run:
Is it a living animal, living plant, or non-living thing?
living animal
Does it have feathers, fur, or neither?
fur
is it domesticated?
yes
BUILD SUCCESSFUL (total time: 30 seconds)
You do not have use the if else correctly may be proper indenting and commenting can also help you in this case.
System.out.println("Think of Something");
System.out.println("Is it a living animal, living plant, or non-living thing? ");
String user = get.nextLine();
// start method
if (user.equals("living animal")); { //starts animal tree
System.out.println("Does it have feathers, fur, or neither?");
String user2 = get.nextLine();
if (user2.equals("feathers")); {
System.out.println("is it bigger than a soccer ball?");
} else if (user2.equals("fur")); {
System.out.println("is it domesticated?");
}
} else if (user.equals("living plant")); { //starts plant tree
System.out.println("is it a tree?");
} // end method
I have a class with a method that calls a method located in another class, and that method has switch cases. Th e problem is that I am not able to exit from the method with switch cases and get back to the next line after the method that called it. I have searched StackOverFlow for similar questions. I also tried to use the suggested solutions in those answers to questions related to exit from a switch case (using a conditional, using return, etc). Unfortunately, when I use these solutions, I don't go back to the next line in the method that called the switch case method. Rather, I am exiting the whole program with "Build Succeeded message".
Rather than being too abstract, I hope I am not flamed for posting some classes simulating the real problem I am facing. Sorry if the code is too long.
public class TestClass {
ClassWithriginalMethod test;
public static void main(String[] args) {
ClassWithriginalMethod g = new ClassWithriginalMethod();
g.presentMenuOptions();
}
}
This class contains the main method.
The next class is the one which have a method that calls the method with switch cases:
import java.util.ArrayList;
import java.util.Scanner;
public class ClassWithriginalMethod {
private final ArrayList<ClassWithSwitchCases> arr;
Scanner s = new Scanner(System.in);
public void presentMenuOptions() {
System.out.println(
"_____________________________________________________________________________\n"
+ "This Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to get create submenu\n"
+ "2: to get edit sub menu\n"
+ "3: to get view sub menu\n"
+ "4: to get delete sub\n"
+ "5: to exit this operation\n"
+ "_____________________________________________________________________________\n");
String str= s.nextLine();
switch (str) {
case "1":
System.out.println("Entering creation...");
this.createMenu();//This method is working properly and user is moved to nextline, i.e shown the presentMenuOptions().
break;
case "2":
System.out.println("Entering editing...");
/* The below method is the damn method that calls the other class methods with swith cases.*/
this.editMenu();
/*
** What I want is to reach the next methos below this comment when I get back from the switch case.
*/
System.out.println("We've exited from the othe class method with switch cases...");
this.presentMenuOptions();
break;
case "3":
System.out.println("Entering viewing...");
this.viewMenu();
this.presentMenuOptions();
break;
case "4":
System.out.println("Entering deletion...");
this.deleteMenu();
this.presentMenuOptions();
break;
default:
System.exit(0);
}
}
public ClassWithriginalMethod() {
this.arr = new ArrayList<>(0);
}
private void createMenu() {
ClassWithSwitchCases toBeCreated = new ClassWithSwitchCases();
this.arr.add(toBeCreated);
this.checkingArraySize();
this.presentMenuOptions();
}
private void editMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index\n");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeEdited = this.arr.get(i); //supposedly I am checking through another function if the object of index i is in the array.
toBeEdited.edit(toBeEdited); // it is here where we are calling the switch method in the other class
//this.presentMenuOptions();
}
private void viewMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeViewed = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
toBeViewed.view(toBeViewed); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void deleteMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
int i = s.nextInt();
ClassWithSwitchCases deleted = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
deleted.view(deleted); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void checkingArraySize () {
if (this.arr.size() <= 0) {System.out.println("There are no objects in the aray");}
else {
arr.stream().map((p) -> {
System.out.println("The following objects are available.");
return p;
}).forEachOrdered((p) -> {
System.out.printf("%-15s\t%-15s\t%-15s\n", "index", "fName", "sName");
System.out.printf("_____________________________________________________________________________\n");
System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName());
});
}
}
}
The last class is the one with switch cases:
public class ClassWithSwitchCases {
private String fName;
private String sName;
Scanner s = new Scanner(System.in);
public ClassWithSwitchCases() {
System.out.println("Please enter first name");
this.fName = s.nextLine();
System.out.println("Please enter sur name");
this.sName = s.nextLine();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
System.out.println("Please enter first name");
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
System.out.println("Please enter sur name");
this.sName = sName;
}
public void edit(ClassWithSwitchCases o) {
System.out.println(
"_____________________________________________________________________________\n"
+ "The Edit Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to edit the object's first name\n"
+ "2: to edit the object's sur name\n"
+ "3: to exit this menu\n"
+ "_____________________________________________________________________________\n");
do {
switch (s.nextLine()) {
case "1":
o.setfName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o); // put so that we can make other edits.
break;
case "2":
o.setsName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o);
break;
case "3":
System.out.println("We are leaving the method with switch cases...");
break;
default:
System.out.println("We are also leaving the method with switch cases...");
break;
}
} while ((Integer.getInteger(s.nextLine()) <= 3) && (Integer.getInteger(s.nextLine()) > 0));
}
public void view(ClassWithSwitchCases o) {
System.out.println(o.toString());
}
#Override
public String toString() {
return "_____________________________________________________________________________\n"
+ "First Name:" + this.getfName() + "\n"
+ "Middle Name:" + this.getsName() + "\n"
+ "_____________________________________________________________________________\n";
}
}
If you try to work these classes, you will notice:
I am able to execute the createMenu() method, and then I get the presentMenuOptions() method, as supposed to be.
The viewMenu() and deleteMenu() methods do their work, but they exit from the whole program.
The editMenu() method is giving me nullPointerExeption, but I have no idea which pointer is that.
I have indicated in the comments in the code what I was thinking of.
I added extra System.out.println() messages, as a way to debug my code. Since I am only a beginner, this is as far as I can go at this stage.
If there is any general value from my question it is: How to exit from a method with switch cases and go back to another method, not necessarily the main method.
Many thanks for you help and patience :)
You can use the return statement anywhere in the switch. Most likely, you want to change your break statements to return statements.
It seems to me that while my question is valid, it is not the core problem. The core problem is how do I envision my classes (Objects) and how they are related to each other. In other words, I faced this problem because of the way I orchestrated my solution. If I chose another orchestration (i.e, more proper design patterns), most probably I was not going to face this issue.
It also seems to me that beginners (I am one of them) who are serious to build a big solution will face this "problem pattern" (asking either silly questions, or evading questions like "Why you are doing this? What were you aiming to achieve?" because they run quickly into implementing certain classes while they have not figured out the overall structural, behavioral, and creational aspects of the solution.
Interestingly, though, is that by making these mistakes, they learn.
Thanks for those who answered me and those who will answer or comment.