Java - Error catching user-input with enums - java

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

Related

I am writing a Java program that is meant to play a version of 20 questions with the user based on their input

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

Exiting a method with switch case in a class to the method that called it in another class

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.

Java enums as integers, Scanner, and menu options

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]

Instance variable with the same value for different objects although different values were assigned

First of all and before posting my question let me ask you people to stop downvoting my questions even if they seem stupid to you ,this site is an important place for me, it helps me a lot with my java doubts which are many,a question ban would be an heavy setback for me, so be helpful even by not answering!
Now for the question,
I have this method were i assign a value to a setter method with user input
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
this method is later called in main from object p1 and object p2 and being assigned a differend value for each one to the instance variable name
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
but when i call the getName() method at the end of main both p1 and p2 have the same value!
Shouldn't each object get it´s own copy of an instance variable?
The Problem is in your addName()-function. Your running your loop(while (!answer.equals("y") || (!answer.equals("n")))) until a y or n is entered. So as soon as you enter it, your loop will stop.
In your loop your checking if the input that was made cotains a y or n. Now the problem should be clear. Your loop won't run with those two values entered, but inside the loop you want to check if one of those is entered.
Two little personal hints(everyone has another style): Don't use break; let your loops end themselfs. Do it with an boolean-variable and updating it's state.
The second hint would be to use one Scanner-Object. For example you could add a Scanner-parameter to your addName-function. Just init one in your MainClass.
Those hints and fixes of the problem applied to your code could look like that:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
And your MainClass:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Hope that helps!

Passing a value from one case to another in switch statement

So here is a sample code :
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please type in a number");
Scanner in = new Scanner(System.in);
switch (in.nextInt()){
case 1:
save(in);
break;
case 2:
System.out.println(value);
break;
default:
System.out.println("Default case");
break;
}
in.close();
}
public static String save(Scanner in){
System.out.println("Type in a word");
String value = in.next();
return value;
}
}
In this particular situation all I am trying to do here is to have access to the value that was stored in case 1.
switch statement in all c-like languages including java is very general. It jumps to label according to the value of switch variable and then continues until break statement appears.
I am not sure what did you meant in your long explanation but in following example:
switch(op) {
case ONE:
foo();
case TWO:
bar();
break;
case THREE:
aaa();
qqq();
break;
}
op == ONE first method foo() will be called, then the flow will arrive to block of TWO because no break statement was written in ONE, so bar() will be called. However then the break statement will jump the flow to code that appears just after the switch.
This is a short explanation. For more details find a good book or tutorial and read chapter about switch statement.

Categories