How to use an object reference in a whole class - java

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.

Related

Local variable may have not been initialized in switch case

I've initialized the variable I wanted, but after adding it's values through a switch case, I cannot return it. Is there any solutions?`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Masukkan nilai a = ");
int a = input.nextInt();
System.out.print("Masukkan nilai b = ");
int b = input.nextInt();
System.out.print("Mau diapain bang angkanya? ");
String o = input.next();
int hasil;
switch (o) {
case "+":
hasil = a + b;
break;
case "-":
hasil = a - b;
break;
case "*":
hasil = a * b;
break;
case "/":
hasil = a / b;
break;
default:
System.out.println("Operator tidak valid");
}
// Error is here, stating that I haven't initialized the variable
System.out.println(hasil);
}
}
`
I've tried putting the console out in each of the case, and it did worked. So, is my first way of doing it is not working?
It shows that error because you declared them but didn't initialized them.
Your variable should be initialized as int hasil = 0;
Check this reference for a better idea. This user has explained it very smoothly.
init your int hasil = 0; or assign a value for it in the default case
default:
hasil = 0;
System.out.println("Operator tidak valid");

Cannot find symbol when already declared

Please someone help me on this error :
import java.util.*;
class Cinema
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
int t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
int t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
int t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}
I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it
You need to declare your variable before switch block for it to be accessible outside of the switch block ... please see the below
import java.util.*;
public class Cinema {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
int t = 0;
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}
Your 't' variable is declared within the case blocks repeatedly, which creates different variables. In this case, it can be seen only inside those blocks. You might consider putting the variable declaration before your switch block.
The variable t is being declared inside the switch statement in the code above which is resulting in the error.You need to initialize it outside and change the value inside the switch statement accordingly.
import java.util.*;
public class Main {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
int t=0;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}
Ok i figured it out, i had to put int t = 0; after the switch block not before.
When i put it before the switch block, it said variable t is already defined in main(Java.lang.String[]). The correct code is as following :
import java.util.*;
class Cinema
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int cat;
System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
cat = sc.nextInt();
switch(cat)
{
case 1:
{
System.out.println("You have selected Premium");
int t = 150; /* VARIABLE DECLARED */
break;
}
case 2:
{
System.out.println("You have selected Gold");
int t = 200; /* VARIABLE DECLARED */
break;
}
case 3:
{
System.out.println("You have selected Business Class");
int t = 400; /* VARIABLE DECLARED */
break;
}
default:
System.out.println("Invalid Option");
break;
}
Scanner num = new Scanner(System.in);
int n, amt;
int t = 0;
System.out.println("Choose number of tickets");
n = num.nextInt();
amt = t * n; /* ERROR : cannot find symbol - variable t */
System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
}
}

Error handling with strings java

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
}

Java exception handling Do loop not working?

Here is the code:
package classes;
import java.util.*;
public class Introduction {
Scanner Input = new Scanner(System.in);
int classChoose;
boolean repeat = false;
public void Introduction() {
System.out.println("\t===THE QUEST FOR PERSEPOLIS===\tv 1.0\n");
System.out.println("Please choose a class: ");
System.out.print("(1)Elite Knight\t");
System.out.print("(2)Dawnguard\n");
System.out.print("(3)Archer\t\t\t");
System.out.print("(4)Barbarian\n");
System.out.print("(5)Mage\t\t\t");
System.out.print("(6)Swordsman\n");
System.out.println("(7)Crossbowman\t");
do {
try {
repeat = false;
classChoose = Input.nextInt();
while(classChoose < 1 || classChoose > 7) {
repeat = false;
System.out.println("Error. Enter a number between 1 and 7(inclusive).");
classChoose = Input.nextInt();
}
}
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine();
}
}while(repeat = true);
switch(classChoose) {
case 1: chooseKnight();
break;
case 2: chooseGuard();
break;
case 3: chooseArcher();
break;
case 4: chooseBarbarian();
break;
case 5: chooseMage();
break;
case 6: chooseSwordsman();
break;
case 7: chooseCrossbowman();
break;
}
}
public static void chooseKnight() {
System.out.println("You have chosen the Elite Knight. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseGuard() {
System.out.println("You have chosen the Dawnguard. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseArcher() {
System.out.println("You have chosen the Archer. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseBarbarian() {
System.out.println("You have chosen the Barbarian. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseMage() {
System.out.println("You have chosen the Mage. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseSwordsman() {
System.out.println("You have chosen the Swordsman. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseCrossbowman() {
System.out.println("You have chosen the Crossbowman. You will be briefed and then you shall be set "
+"on your quest!");
}
}
Everytime I run it, the program prompts me to choose my class. After I enter my choice, the program does not go on to the switch statement below the do loop. Can someone help me fix this?
-Calvin
This is an assignment:
while(repeat = true); // Note single '=', not '=='
and the result of which will always be true, from section 15.26 Assignment Operators of the Java Language Specification:
At run time, the result of the assignment expression is the value of the variable
after the assignment has occurred.
Change to:
while(repeat);
while(repeat = true);
should be: -
while(repeat == true); // Or better: - while(repeat);
And in your catch, change Input.nextLine() to Input.next() : -
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine(); // Change to Input.next()
}
And your instance variable should begin with a lowercase alphabet or an underscore.. So change Input to input.

How to get and set value in the switch-case statement

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
}
}
}

Categories

Resources