Im new to java and trying to write a switch. Where depending on a value of guess different prize will be given. I'm doing something wrong because compiler says variable already defined. But how can I not define it, so that switch knows what value to look for to give what prize?
if (guess == randomNom)
{
System.out.println(" You Win! ");
player.setEarning(player.getEarn() + guess * 10);
int reward = guess;
String prize = "";
switch(reward)
{
case 1: int reward = 10;
String prize = " Prize #1";
break;
case 2: int reward = 20 ;
String prize = "Prize #2";
break;
case 3: int reward = 30;
String prize = "Prize #3";
break;
...
}
compiler say OK, You try to create 'another variable with the same name', whats wrong. Delete duplicated declarations
if (guess == randomNom)
{
System.out.println(" You Win! ");
player.setEarning(player.getEarn() + guess * 10);
int reward = guess;
String prize = "";
switch(reward)
{
case 1: reward = 10;
prize = " Prize #1";
break;
case 2: reward = 20 ;
prize = "Prize #2";
break;
case 3: reward = 30;
prize = "Prize #3";
break;
...
}
The problem is in these lines
String prize = "";
String prize = " Prize #1";
String prize = "Prize #2";
When you Assign a variable in above manner i.e. data type followed by variable name compiler assumes that you want to define a new variable with some value.
Instead, you should define it once
String prize = ""; // Data type followed by variable name is to define new variable
and update subsequently
prize = " Prize #1"; //just the variable name with assignment operator to assign new value to existing variable.
prize = " Prize #2";
Related
I will show you my code without any classes.
I need it divided in 3 classes which are Main class , First class , Second class.
for example ,
the main class
products class
and coding class maybe
package vending.machine.project;
import java.util.Scanner;
public class VendingMachineProject {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n=1;
int x=1;
int exit=0;
double price = 0;
double tax = 0.15;
char choice;
double finPrice=0;
while(exit!=-1)
{
while(n!=5)
{
if(n>0&&n<5)
{
System.out.print("1.Hot Drinks\n2.Soft Drinks\n"
+ "3.Chips\n4.Sweets\n5.Exit\n\n");
System.out.print("Choose one of the types above: ");
n = keyboard.nextInt();
switch(n)
{
case 1:
System.out.print("1.Hot Chocolate (5$)\t\t\t2.Tea (2$)\n3.Caramel Latté (7$)\t\t\t"
+ "4.Turkish Coffee (6$)\n5.Espresso (8$)\t\t\t\t6.Green Tea (3$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 5;
break;
case 2:
price = price + 2;
break;
case 3:
price = price + 7;
break;
case 4:
price = price + 6;
break;
case 5:
price = price + 8;
break;
case 6:
price = price + 3;
break;
}
}
else
System.out.print("Please choose one of"
+ " the hot drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 2:
System.out.print("1.Cocacola (2$)\t\t\t2.PEPSI (3$)\n3.Seven UP (1$)\t\t\t"
+ "4.Code Red (4$)\n5.Sprite (1$)\t\t\t6.Mirinda (2$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 2;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 1;
break;
case 4:
price = price + 4;
break;
case 5:
price = price + 1;
break;
case 6:
price = price + 2;
break;
}
}
else
System.out.print("Please choose one of"
+ " the soft drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 3:
System.out.print("1.Lays (1$)\t\t\t2.Chips Oman (3$)\n3.Cheetos (3$)\t\t\t"
+ "4.Doritos (2$)\n5.Bugles (2$)\t\t\t6.AL Batal (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 2;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the Chips above Sir: ");
}while(!(x>0&&x<7));
break;
case 4:
System.out.print("1.Oreo (1$)\t\t\t2.Kinder (4$)\n3.Bounty (3$)\t\t\t"
+ "4.Twix (3$)\n5.Galaxy (2$)\t\t\t6.Biscream (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 4;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 3;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the sweets above Sir: ");
}while(!(x>0&&x<7));
break;
case 5:
exit = -1;
break;
}
System.out.print("Do you want to order anything more Sir?"
+ "type (y). If not Type (n) to Exit: ");
do{
choice = keyboard.next().charAt(0);
Character.toLowerCase(choice);
if(choice=='n'){
n = 5;
exit = -1;
}
else if(choice!='y'){
System.out.print("Please Sir choose (y) or (n): ");
}
}while(choice!='y'&&choice!='n'&&n!=5);
}
else {
System.out.print("Please choose from the list Above: ");
n = keyboard.nextInt();
}
}
}
}
}
You need to study the basics of object-oriented programming.
There is no one exact best way to organize your code into classes. Even separating the better ways from the less optimal ways takes more information about the business that you have given here. But let's walk though the basics to get you going.
Look for the things, the entities, from the real world that you are modeling in your app. Then list the attributes, the properties, that describe each particular entity.
I see products (food items) as an entity. Each product has a name, a price, and a category (hot drink, cold drink, chips, candy, and so on, as its attributes.
So write a class called Product to represent each product you are selling. In Java 16 and later, you might use a record to more briefly write the class. A record is appropriate only for a class whose main purpose is to merely communicate data transparently and immutably, with a focus on state rather than behavior, and no inheritance.
public record Product ( String name , int price , String category ) {}
If you were further advanced, I'd suggest an enum for the category. But for now use a String with text.
Instantiate your products.
Product oreo = new Product( "Oreo" , 1 , "Cookie" ) ;
Another entity is the vending machine. The vending machine holds a list of products. Make another class for this.
public class VendingMachine
{
// Member fields.
final private List< Product > products ;
…
// Constructor.
public VendingMachine()
{
this.products =
List.of(
new Product( "Oreo" , 1 , "Cookie" ) ,
new Product( "Turkish Coffee" , 6 , "Hot drink" ) ,
…
)
;
…
}
// Methods.
…
public List< Product > getProductsForCategory( String category )
{
… Loop all the products to find the ones whose assigned category matches this desired category.
}
}
That vending machine object knows how to search its list of products to produce a subset of products by category. So we have the getProductsForCategory method. That method returns an ordered collection, a List.
VendingMachine vendingMachine = new VendingMachine() ;
…
List< Product > cookies = vendingMachine.getProductsForCategory( "Cookie" ) ;
You might want a sort-order field, just an integer number, as another member field on your Product class if the business (your client) wants to list certain products ahead of others. With such a field, the getProductsForCategory method could sort the products.
Next we need to present each category’s list of products to the user. So we need a user-interface.
Make another class to interact with the user via the console. The UI class knows about public interface of the vending machine object, but the vending machine does not know about the console nor the user. The vending machine only knows about the products it offers.
The UI object will access each category of products from the vending machine, getting a list. The UI object will loop through those objects to present a menu to user. Based on user's feedback, the UI object builds a collection of the products and quantities ordered by the user. You might write another class for this "shopping cart" or "order pad" of the user's choices, with a total price calculated.
In more realistic work, a vending machine would also need to manage its inventory. But I suppose that aspect is outside the scope of your schoolwork assignment.
This question already has answers here:
Case insensitive matching in Java switch-case statement
(5 answers)
Closed 2 years ago.
So, I'm trying to make a simple menu with switches.
I have a letter choice inside it. I'm using next().charAt(0); to scan a letter.
It worked well, but I want to simplify it. you see, I have to make a case each choice both uppercase and lowercase.
So how to ignore case so I don't have to make both cases?
Also note: I'm using the old version of Java and Netbeans 8.2 as my IDE. (because my college keeps insisting not to use the newer one. Probably because they don't have the textbook yet.), so probably newer syntax wouldn't work.
my code:
import java.util.Scanner;
public class NewClass2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
char milk;
int s, h, price;
h = 0;
price = 0;
String type, size;
System.out.println("NutMart");
System.out.println("Milk selections:\n A. Milk A \n\t 1. Regular ($10) \n\t 2. Medium ($20) \n\t 3. Large ($30)");
System.out.println(" B. Milk B \n\t 1. Regular ($15) \n\t 2. Medium ($30) \n\t 3. Large ($45)");
System.out.println(" C. Milk C \n\t 1. Regular ($20) \n\t 2. Medium ($40) \n\t 3. Large ($60)");
System.out.println("Insert Milk Type: ");
milk = input.next().charAt(0);
switch(milk){
case 'a':
type = "Milk A";
h = 10;
break;
case 'b':
type = "Milk B";
h = 15;
break;
case 'c':
type = "Milk C";
h = 20;
break;
case 'A':
type = "Milk A";
h = 10;
break;
case 'B':
type = "Milk B";
h = 15;
break;
case 'C':
type = "Milk C";
h = 20;
break;
default:
System.out.println("Invalid!");
System.out.println("Please select the correct choice: ");
milk = input.next().charAt(0);
break;
}
System.out.println("Select the size: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
switch(s){
case 1:
size = "Regular";
price = h * 1;
break;
case 2:
size = "Medium";
price = h * 2;
break;
case 3:
size = "Large";
price = h * 3;
break;
default:
System.out.println("Invalid");
System.out.println("Please select the correct choice: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
break;
}
System.out.println("Individual Price: $" + price);
System.out.println("Please insert the quantity: ");
while (!input .hasNextInt()) input .next();
int quantity = input.nextInt();
int total = price * quantity;
System.out.println("Your total will be $" + total );
}
}
Note, that in this case converting to a consistent case is the best was to achieve your goal. But when you have a variety of results for dissimilar inputs in a switch statement you can do the following for case constructs.
case 'a':
case 'A:
type = "Milk A";
h = 10;
break;
...
The case will simply fall thru whether 'a' or 'A' was provided.
Prompt: "Write a program to play the pig game against the computer. At each turn, the current player will
roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your
opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player
rolls a 1, all the points accumulated for that round are forfeited and the control of the dice
moves to the other player. If the player rolls two 1s in one turn, the player loses all the points
accumulated thus far are forfeited and the control moves to the other player. The player may
voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll
again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the
other player to win. Computer is going to flip a coin to choose the first player "
My problem: I got the program to output that either the computer or the player is going first based on a coin flip. However, how would I actually prompt the program to run a method of the person chosen to start first, and then how would I switch between the computer and player at the end of each turn? Btw, I know this code is incomplete, but I hope that my question makes sense.
Code so far:
import java.util.*;
public class NavaiPigGame
{
public static final int POINT = 30;
public static final int FORFEIT_POINTS = 20;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
play(rand,input);
}
// desription of game
public static void description()
{
System.out.println("***********************************************************************************");
System.out.println("Write a program to play the pig game against the computer. At each turn, the current player will");
System.out.println("roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your");
System.out.println("opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player");
System.out.println("rolls a 1, all the points accumulated for that round are forfeited and the control of the dice");
System.out.println("moves to the other player. If the player rolls two 1s in one turn, the player loses all the points");
System.out.println("accumulated thus far are forfeited and the control moves to the other player. The player may");
System.out.println("voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll");
System.out.println("again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the");
System.out.println("other player to win. Computer is going to flip a coin to choose the first player");
System.out.println("***********************************************************************************");
System.out.println("lets start the fun");
}
//flips a coin and decides who starts the game
public static String flipCoin(Random rand)
{
int coin = rand.nextInt(2);
String comp = "";
switch (coin)
{
case 0: comp = "heads";
break;
case 1: comp = "tails";
break;
}
return comp;
}
public static int rollDice(Random rand)
{
int dice1 = rand.nextInt(6)+1;
int dice2 = rand.nextInt(6)+1;
System.out.println("Dice 1: " +dice1);
System.out.println("Dice 2: " +dice2);
return dice1+dice2;
}
// select a random name of the computer via arrays
public static String nameComputer(Random rand)
{
int name = rand.nextInt(10);
String compName = "";
switch (name)
{
case 0: compName = "Lisa";
break;
case 1: compName = "Kathy";
break;
case 2: compName = "Hali";
break;
case 3: compName = "Jack";
break;
case 4: compName = "Alex";
break;
case 5: compName = "Max";
break;
case 6: compName = "Jill";
break;
case 7: compName = "James";
break;
case 8: compName = "Martha";
break;
case 9: compName = "Lauren";
break;
}
return compName;
}
public static void play(Random rand, Scanner input)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
boolean gameOver = false
boolean turnOver = false
description();
String compName = nameComputer(rand);
System.out.println("Hi my name is " + compName);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hi " + name + ", I am flipping the coin to determine who goes first");
System.out.print("press any key to start the game. ");
input.nextLine();
String flip = flipCoin(rand);
int turn;
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
}
}
}
Create :
A playTurn(int turn) function (1 for the player, 0 for the computer) that handle a play turn (roll dice, calculate point etc.)
A boolean function that check wether there is a winner or not. Example : isWinner(int player) (again, 1 for the player, 0 for the computer)
Use the function a first time in your if() else statment like that :
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
playTurn(turn);
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
playTurn(turn);
}
Then you can add :
do {
if(turn == 1){
turn = 0;
playTurn(turn);
}else{
turn == 1;
playTurn(turn);
}
while ( !isWinner(1)|| !isWinner(0) );
This is not very well designed, but it should hopefully give you a hint on what to do next.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().