I want to make a simple menu with 3 choices:
'Create new employee', 'Display all employees' and 'Quit' in a Employee Manager(code below) but it was not successful(compiling error).
BlueJ editor cannot realize the object 'm', 's' and 'l' in the 'case 2' statement. Is there anyway to get the value of the object in the 'case 1' and use them in the 'case 2'? Thanks a lot!
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int ch;
do{
System.out.println("EMPLOYEE MANAGER\n");
System.out.println("1. Create new employees\n");
System.out.println("2. Display all employees\n");
System.out.println("3. Quit\n");
System.out.print("Your choice: ");
Scanner input = new Scanner(System.in);
ch = input.nextInt();
switch(ch){
case 1: System.out.println("== CREATE NEW EMPLOYEES ==");
System.out.println();
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
m.newManager();
s.newScientist();
l.newLabourer();
System.out.println();
break;
case 2: System.out.println("== PREVIEW EMPLOYEES ==");
System.out.println();
m.display();
s.display();
l.display();
System.out.println();
System.out.println();
break;
case 3: System.exit(0);
default: System.out.println("Invalid choice!");
}
} while(ch >= 1 && ch <=4);
}
}
They are local to block, declare them out of switch block
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
switch(){...}
This answers your question well, but I would like to add few more details
if you don't put brackets with case block like
switch(i){
case 1:
String str="abc";
System.out.println(str);
case 2:
// it will give you compile time error
//duplcate local variable str
String str="abc";
}
then this str instance is visible in other case blocks as well
Q: Is there anyway to get the value of the object in the 'case 1' and use them in the 'case 2'?
A: No. The whole point of a case block is "either-or".
If you want to do "something" based on "something else", then you'll need two separate control structures.
EXAMPLE:
import java.util.Scanner;
public class Test
{
Manager m = null;
Scientist s = null;
Labourer l = null;
public static void main(String[] args) {
Test test = new Test().doIt ();
}
private void doIt () {
int ch;
do{
System.out.println("EMPLOYEE MANAGER\n");
System.out.println("1. Create new employees\n");
System.out.println("2. Display all employees\n");
System.out.println("3. Quit\n");
System.out.print("Your choice: ");
Scanner input = new Scanner(System.in);
ch = input.nextInt();
switch(ch) {
case 1:
System.out.println("== CREATE NEW EMPLOYEES ==");
getEmployees ();
break;
case 2:
System.out.println("== PREVIEW EMPLOYEES ==");
previewEmployees ();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
}
} while(ch >= 1 && ch <=4);
}
private void getEmployees () {
System.out.println();
m = new Manager();
s = new Scientist();
labourer l = new Labourer();
m.newManager();
s.newScientist();
l.newLabourer();
System.out.println();
}
private void previewEmployees () {
...
}
Define your objects m, s and l in a broader scope outside the switch. Also, initialize your objects with null value and validate them before using.
Manager m = null;
Scientist s = null;
Labourer l = null;
do{
//your code here....
switch(ch) {
case 1:
m = new Manager();
//the rest of your code here...
break;
case 2:
if (m != null) {
m.display(); //and so on
}
}
}
Related
I have to make a Java program using scan, switch and cases in which I can add one customer with a command "add" and remove one customer with a command "remove".
The default number of customers in queue is 5. If the count of customers gets larger than 8 it prints out "This queue is too big." If there is less than 1 customer it prints out "There's nobody in the queue."
I tried to do some of the code, but I have no idea what to do next.
import java.util.Scanner;
public class fronta {
public static void main(String[] args) {
System.out.println ("This queue has 5 people in it at the moment.");
Scanner scan = new Scanner(System.in);
boolean x = true;
String b = "ADD";
int a = 5;
b = scan.nextLine();
while(x){
switch (b) {
case "ADD":
System.out.println ("This queue has " + a + " people in it at the moment.");
b = scan.nextLine();
System.out.println ("This queue is too big");
break;
default:
case "EXIT":
System.out.println("End of simulation.");
x = false;
break;
}
}
}
}
I think you need somehting like below:
public static void main(String[] args) {
boolean isExitRequested = false;
int queueSize = 5;
System.out.println ("This queue has "+queueSize+" people in it at the moment.");
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
String input = scan.nextLine();
switch (input){
case "ADD":
System.out.println ("This queue has " + queueSize++ + " people in it at the moment.");
if (queueSize > 8) {
System.out.println("This queue is too big");
}
break;
case "REMOVE":
if (queueSize == 0){
System.out.println("There's nobody in the queue.");
} else {
queueSize--;
}
break;
case "EXIT":
isExitRequested = true;
break;
default:
System.out.println("Unknown input: "+input);
}
if(isExitRequested)
break;
}
}
I have a program which plays a game of superhero top trumps and I need to repeat the menu every time a user plays the game. I've tried to create a method (displayMenus) which would be inserted into every switch statement (except for closing the program), however I don't understand how to get it to return this menu.
public class Heros {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int index = 0;
do {
int inp = input.nextInt();
switch (inp) {
//FIRST
case 1:
index = 0;
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//NEXT
case 2:
index++;
if (index > HerosAsList.getHeros().size() - 1) {
index = HerosAsList.getHeros().size() - 1;
}
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//PREV
case 3:
index--;
if (index < 0) {
index = 0;
}
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//LAST
case 4:
index = HerosAsList.getHeros().size() - 1;
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//QUIT
case 0:
System.out.println("Closing system");
System.exit(inp);
break;
}
}
while(index<HerosAsList.getHeros ().size());
}
public static displayMenus () {
System.out.println("First - 1");
System.out.println("Next - 2");
System.out.println("Prev - 3");
System.out.println("Last - 4");
System.out.println("Quit - 5");
System.out.println("");
System.out.println("Enter Choice:");
}
}
any help is greatly appreciated, I just can't seem to get my head around methods!
Firstly, the declaration of displayMenus is invalid. You need to give it a return type (even if that is void), e.g.:
public static void displayMenus () {
If you make it void, you would need to invoke displayMenus() without calling System.out.println:
displayMenus();
If you make it String, you would need to build a String in displayMenus and return it, e.g.:
public static String displayMenus() {
return "First - 1" + ...;
}
then you can invoke System.out.println(displayMenus()).
Just change displayMenus to return the menu as a String, rather than printing it:
public static String displayMenus() {
return "First - 1\nNext - 2\nPrev - 3\nLast - 4\nQuit - 5\n\nEnter Choice:\n";
}
I simplified the code down, because there were quite a few syntax errors in the code itself, but this should answer your question. Your displayMenus() function doesn't need to return a String, you can instead call this at the beginning of your do...while loop. The logic flow should be:
Initialize scanner
Create variable for choice
Enter do...while loop
Call displayMenus()
Read user choice from scanner
Do switch logic
Back to 3rd item if the loop isn't broken
I made a small class to demo this:
package zzzTestProj;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
int userMenuChoice;
do {
displayMenus();
userMenuChoice = userInputScanner.nextInt();
switch (userMenuChoice) {
// FIRST
case 1:
break;
// NEXT
case 2:
break;
case 0:
System.out.println("Closing system");
System.exit(userMenuChoice);
break;
}
} while (userMenuChoice != 5);
}
public static void displayMenus() {
System.out.println("First - 1");
System.out.println("Next - 2");
System.out.println("Prev - 3");
System.out.println("Last - 4");
System.out.println("Quit - 5");
System.out.println("");
System.out.print("Enter Choice:");
}
}
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}
so for example in a switch statement "case 1" I declare an Object reference variable, its all good, but if I try to use in a "case 2" it says that reference variable cannot be resolved.
How can I use it in every case?
Edit:
switch(choice){
case 1: {
if(HotelObj.getClassicRoomsAvailable() == 0 && HotelObj.getExecutiveRoomsAvailable() == 0){
System.out.println("Sorry, there are no available rooms");
break;
}else {
Scanner scanInput = new Scanner(System.in);
System.out.print("\nEnter desired room type: ");
System.out.print ("\nEnter \"Classic\" for a classic type room, price: 90$ for a day");
System.out.println("\nEnter \"Executive\" for a executive type room, price: 150$ for a day");
String roomChoice = scanInput.nextLine();
System.out.print("Enter your name: ");
String clientName = scanInput.nextLine();
System.out.print("Enter for how many days you'll stay:");
int stayingDays = scanInput.nextInt();
Client ClientObj = new Client(clientName, roomChoice, stayingDays);
Client.clientCount++;
if(roomChoice.equals("Classic")){
ClientObj.clientRoom = new Room("Classic");
ClientObj.setMoney(ClientObj.getMoney()- stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decClassicRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
} else {
ClientObj.clientRoom = new Room("Executive");
ClientObj.setMoney(ClientObj.getMoney()-stayingDays * ClientObj.clientRoom.getPrice());
HotelObj.decExecutiveRooms(1);
HotelObj.addIncome(stayingDays*ClientObj.clientRoom.getPrice());
}
}
break;
}
case 2: {
System.out.println("Name: "+ClientObj.getName());
//Error "ClientObj cannot be resolved"
}
}
Variables you declare inside your case statements are local to that statement, so, right-o, they won't be seen outside it. Just declare your variable before (above) the switch() and it'll be visible to them all.
Edit: this example is in response to Brian Roach below:
public void main(String[] args) {
int foo = 11;
switch (foo) {
case 1: {
int bar = 12;
System.out.println("1");
break;
}
case 2: {
System.out.println("2");
System.out.println("bar: " + bar);
break;
}
default: {
System.out.println("default");
break;
}
}
Compiler complains: "bar cannot be resolved to a variable"
To fix, move the declaration of bar to the same location as the declaration of foo.
I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.