This code should display a menu and afterwards it should give the user the possibility to choose from the menu. The user can choose 3 items along with the quantity and afterwards the total price is displayed and the program stops.
This is what the program should look like when it runs:
This is the menu for Tal'Qroq Restourant:
This is the menu of pizzas
A.Margherita ..... $5.50
B.Capricosa ..... $6.50
C.Funghi ..... $7.00
D.Vegeterian..... $7.00
E.Tropical..... $8.00
F.Meat ..... $8.00
G.Salami..... $8.00
H.Maltija..... $8.00
I.Calzona..... $8.50
J.Tal'Qroq special..... $8.00
Enter your pizza order according to the menu letters:
After the user inputs the pizza the quantity is asked and that works fine.
The user must be asked 3 times to enter the pizza and quantity but instead the loop wont stop and keep asking and asking infinitely and this is my problem!
The following is the code:
public class Menu{
public static void main (String[]args){
float total = 0;
char cas = 0;
int quant = 0;
int count = 0;
System.out.println("This is the menu for Tal'Qroq Restourant:");
System.out.println("\n");
System.out.println("This is the menu of pizzas");
System.out.println("\n");
System.out.println("A.Margherita ..... $5.50");
System.out.println("\n");
System.out.println("B.Capricosa ..... $6.50");
System.out.println("\n");
System.out.println("C.Funghi ..... $7.00");
System.out.println("\n");
System.out.println("D.Vegeterian..... $7.00");
System.out.println("\n");
System.out.println("E.Tropical..... $8.00");
System.out.println("\n");
System.out.println("F.Meat ..... $8.00");
System.out.println("\n");
System.out.println("G.Salami..... $8.00");
System.out.println("\n");
System.out.println("H.Maltija..... $8.00");
System.out.println("\n");
System.out.println("I.Calzona..... $8.50");
System.out.println("\n");
System.out.println("J.Tal'Qroq special..... $8.00");
System.out.println("\n");
float a = 5.50f;
float b = 6.50f;
float c = 7.00f;
float d = 7.00f;
float e = 8.00f;
float f = 8.00f;
float g = 8.00f;
float h = 8.00f;
float i = 8.00f;
float j = 8.00f;
do{
System.out.print("Enter your pizza order according to the menu letters: ");
cas = Keyboard.readChar();
System.out.print("Enter the ammount of pizza you want: ");
quant = Keyboard.readInt();
if(cas == 'a' || cas == 'A'){
System.out.println("Total for " + quant + " Margherita is :" + (a*quant));
System.out.println("\n");
total = total + (a*quant);
count = count++;
}else if(cas == 'b' || cas == 'B'){
System.out.println("Total for " + quant + " Capricosa is :" + (b*quant));
System.out.println("\n");
total = total + (b*quant);
count = count++;
}else if(cas == 'c' || cas == 'C'){
System.out.println("Total for " + quant + " Funghi is :" + (c*quant));
System.out.println("\n");
total = total + (c*quant);
count = count++;
}else if(cas == 'd' || cas == 'D'){
System.out.println("Total for " + quant + " Vegeterian is :" + (d*quant));
System.out.println("\n");
total = total + (d*quant);
count = count++;
}else if(cas == 'e' || cas == 'E'){
System.out.println("Total for " + quant + " Tropical is :" + (e*quant));
System.out.println("\n");
total = total + (e*quant);
count = count++;
}else if(cas == 'f' || cas == 'F'){
System.out.println("Total for " + quant + " Meat is :" + (f*quant));
System.out.println("\n");
total = total + (f*quant);
count = count++;
}else if(cas == 'g' || cas == 'G'){
System.out.println("Total for " + quant + " Salami is :" + (g*quant));
System.out.println("\n");
total = total + (g*quant);
count = count++;
}else if(cas == 'h' || cas == 'H'){
System.out.println("Total for " + quant + " Calzona is :" + (h*quant));
System.out.println("\n");
total = total + (h*quant);
count = count++;
}else if(cas == 'i' || cas == 'I'){
System.out.println("Total for " + quant + " Maltija is :" + (i*quant));
System.out.println("\n");
total = total + (i*quant);
count = count++;
}else if(cas == 'j' || cas == 'J'){
System.out.println("Total for " + quant + " Tal'Qroq special is :" + (j*quant));
System.out.println("\n");
total = total + (j*quant);
count = count++;
}else{
System.out.println("Your selection isn't avaliable in our Menu!");
System.out.println("\n");
}
} while (count <= 3);
System.out.println("Your total is €" + total);
}
}
Any answers or help is highly appreciated :).
Your statement count = count++ looks wrong. Use just count++ or count = count + 1.
Using count = count++ creates byte code somewhat like this:
temp = count
count = count + 1
count = temp
So in effect the count is not getting incremented.
Using count = ++count should work, but logically looks wrong:
count = count + 1
count = count
Best not try the funny characteristic of compilers.
int i = 1;
i = i++;
System.out.prinln(i); //-> 1
You just have to write "i++;" and then you are good.
And btw. Never Ever save money in a float or a double ;)
Edit:
int i = 1;
i = ++i;
That would be possible because you are increasing i before you assign the new value.
You have several things that you could improve in your program. First, let's get to the bug, you are saying count = count ++ but by doing this, the compiler will start by incrementing the value of count, and then revert count to its old value, since count++ will be returning not the incremented value. To simplify, this statement does nothing, and do not increment the value of count.
When you want to increment, use the postfix operator:
count++;
By analysing your program, you can notice a lot of duplicate code that could be reduced!
For example, when comparing the inputs, you can use .equals(), this way you don't have to split the case for upper and lowercase:
(cas == 'f' || cas == 'F')
is equivalent to
cas.equals('f')
Which you can repeat for the rest of the cases.
Inside each if statement, you are doing the same system.out.println. For simplicity you can declare a variable for print, like
String typeofPizza;
And then inside each if
typeofPizza = "Margherita";
This way, you can remove the print to the end of the ifclauses:
System.out.println("Total for " + quant + typeofPizza + "is :" + total);
Thank you for your early responses :).The program worked fine. I can't believe a made such a stupid mistake count ++ instead of ++ count.I also had the change int count to 1 instead of 0.
Related
This question already has answers here:
Using variables outside of an if-statement
(2 answers)
Closed 2 years ago.
I'm a student and would like to know if there is a way to take a variable out of its scope block to be used in a local scope? I am trying to code a store of some sort where the users are given a few options to choose what they want to buy, how much they want to buy, and give them the total payment for the same Item. Now outside the block scope, I want to give the overall total with how much they bought of each item. Here's my code:
import java.util.Scanner;
public class SariSariStore{
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
int piattos = 20;
int wRabbit = 1;
int maxEM = 1;
int nescafeO = 7;
float iceW = 1.50f;
System.out.println("Would you like to buy something? [Y/N]");
char i = scanner.next().toLowerCase().charAt(0);
do {
System.out.println("==================================="
+"\n"+ "| Sari Sari Mart |"
+"\n"+ "==================================="
+"\n"+ "| What do you want to buy? |"
+"\n"+ "| |"
+"\n"+ "| 1) Piattos chips 20 Php |"
+"\n"+ "| 2) White Rabbit 1 Php |"
+"\n"+ "| 3) Max extra menthol 1 Php |"
+"\n"+ "| 4) Nescafe Original 7 Php |"
+"\n"+ "| 5) Ice water 1.5 PhP |"
+"\n"+ "| 6) Exit |"
+"\n"+ "===================================");
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
int itotal1 = piattos * quantity1;
System.out.println("Total price: " + itotal1 +" Php");
}else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
int itotal2 = wRabbit * quantity2;
System.out.println("Total price: " + itotal2 +" Php");
}else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
int itotal3 = maxEM * quantity3;
System.out.println("Total price: " + itotal3 +" Php");
}else if (choice == 4){
System.out.print("How many would you like to buy? " );
int quantity4 = scanner.nextInt();
int itotal4 = nescafeO * quantity4;
System.out.println("Total price: " + itotal4 +" Php");
}else if (choice == 5){
System.out.print("How many would you like to buy? " );
int quantity5 = scanner.nextInt();
float itotal5 = iceW * quantity5;
System.out.println("Total price: " + itotal5 +" Php");
}else if (choice == 6){
}
}else{
System.out.println ("Sorry we do not have that item, please pick among the choices");
}
int Total = itotal1 +itotal2 +itotal3 +itotal4 +itotal6; // problematic statement
System.out.println ("Your total is:"+ Total + " Php");
System.out.println ("Do you still want to buy something? [Y/N]");
i = scanner.next().toLowerCase().charAt(0);
}while (i == 'y');
if (i =='n'){
System.out.println("Thank you! Please come again");
}
}
}
Thanks :>
Can't you use just one field for this? Like this:
System.out.println("Please select option from the given choices: ");
int choice = scanner.nextInt();
int total = 0;
if (choice >= 1 && choice <= 6){
if (choice == 1){
System.out.print("How many would you like to buy? " );
int quantity1 = scanner.nextInt();
total = piattos * quantity1;
System.out.println("Total price: " + total +" Php");
} else if (choice == 2){
System.out.print("How many would you like to buy? " );
int quantity2 = scanner.nextInt();
total = wRabbit * quantity2;
System.out.println("Total price: " + total +" Php");
} else if (choice == 3){
System.out.print("How many would you like to buy? " );
int quantity3 = scanner.nextInt();
total = maxEM * quantity3;
System.out.println("Total price: " + total +" Php");
}
...
} else {
System.out.println ("Sorry we do not have that item, please pick among the choices");
System.out.println ("Your total is:"+ total + " Php");
}
Also consider using switch statement for multiple if statements
I'm trying to make a code which counting pages as the user set, the problem is the ListView is skipping some of the row !!
I tried the code alone as a java code and it's work well !!
Here's the code:
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number >= startpage){
HashMap<String,String> data = new HashMap<>();
if(Number == startpage){
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP",NumberofPages + " Pages");
}
if(Number >= startpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From "+Number);
data.put("from", "From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
}
if(Number > endpage | (Number + DailyPages) > endpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day","Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
int value = endpage - Number;
Number += value;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + (value + 1));
data.put("NOP",value + " Pages");
}
if(Number == endpage | (Number + 1) == endpage){
Number = 0;
}
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
And Here's the result (First page is 1, Last is 55) - Skipped the 1st day and 5th day
#Shree Krishna correctly pointed out your mistake and should fix your code accordingly. You can use following as well :-
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number <= endpage){
HashMap<String,String> data = new HashMap<>();
System.out.print("Day Number " + Day);
data.put("day", "Day " + Day);
++Day;
System.out.print("From " + Number);
data.put("from", "From " + Number);
int prevNumber = Number;
Number += DailyPages;
Number = Number > endpage ? endpage : Number;
int NumberofPages = Number - prevNumber + 1;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.print(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
++Number;
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
As your logic in codes, Simply lets take an example if
Num1 = 1
Your condition will be
if(Number == startpage) ---> if(1 == 1) //Condition satisfied
Then what happened is Day is increased by 1 and added to variable data.
Another condition in the same loop
if(Number >= startpage) ---> if(10 >= 1) //Again Condition satisfied
Then again Day is increased by 1
Conclusion
Your every data is being shown with +1 added.
To prevent this
Check your every if condition and make them all unique, Don't make it repetitive in the same condition, OR change the value of startpage too in each condition if it doesn't violate your logic in future.
I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}
This is the assignment that was give to me. But I can't seem to understand what is wrong with my program and how to go about fixing it. It just keeps rolling dice non-stop and freezes my JCreator. I even tried changing the NUMBER value to 10 and it still does the same thing.
I have declared all the variables. You need to add code to simulate rolling the
dice and keeping track of the doubles. Convert the algorithm below to Java and
place it in the main method after the variable declarations, but before the output
statements. You will be using several control structures: a while loop and an if-else-
if statement nested inside another if statement. Use the indenting of the
algorithm to help you decide what is included in the loop, what is included in the
if statement, and what is included in the nested if-else-if statement.
To “roll” the dice, use the nextInt method of the random number generator to
generate an integer from 1 to 6.
You are not using a doop loop correctly. You have a do-loop and while loop, not a single do-loop. In the do-loop count never increases so the loop will never end. A do loop performs the first iteration before evaluating whether to continue.
import java.util.Random;
public class DiceSimulation
{
public static void main(String[] args)
{
final int NUMBER = 10000;
Random generator = new Random();
int die1Value;
int die2Value;
int count = 0;
int snakeEyes = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
do{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
if (die1Value == die2Value)
{
if(die1Value == 1)
{
snakeEyes++;
}
else if (die1Value == 2)
{
twos++;
}
else if (die1Value == 3)
{
threes++;
}
else if (die1Value == 4)
{
fours++;
}
else if (die1Value == 5)
{
fives++;
}
else if (die1Value == 6)
{
sixes++;
}
}
count++;
}while (count < NUMBER);
System.out.println ("You rolled snake eyes " + snakeEyes +
" out of " + count + " rolls.");
System.out.println ("You rolled double twos " + twos +
" out of " + count + " rolls.");
System.out.println ("You rolled double threes " + threes +
" out of " + count + " rolls.");
System.out.println ("You rolled double fours " + fours +
" out of " + count + " rolls.");
System.out.println ("You rolled double fives " + fives +
" out of " + count + " rolls.");
System.out.println ("You rolled double sixes " + sixes +
" out of " + count + " rolls.");
}
}
I think you understood the do-while concept wrong.
The "do {...}" part (where you roll the dice) gets executed as long as the expression inside the while brackets is true.
Move the whole "if (die1Value == die2Value)" part (up to the "counter++;" line) into the do braces, and it should run.
do
{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
}
while (count <= NUMBER);
That first keyword do is taking the while to loop the whole block forever since the count variable is only incremented on the next block.
My advice is to remove the do:
//do
//{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
//}
while (count <= NUMBER)
{
...
}
Since you already have a block after the while.
I am having a problem with my loop and I realise there is probably a slight adjustment needs to be made to get this working the right way but I just cant see what that is! I have included the code below:
final int SIZE = 6;
//array to store user numbers
int [] userNumbers = new int[SIZE];
boolean found = false;
int pos = 0;
boolean bonus = false;
int lottCount = 0;
while (pos<SIZE)
{
System.out.println("enter your numbers");
userNumbers[pos]=keyboard.nextInt();
pos++;
}
for (int count: userNumbers)
{
System.out.println(count);
}
for (int loop = 0; loop <numbers.length; loop++ )
{
for (int loopOther = 0; loopOther < SIZE; loopOther++)
{
if (userNumbers[loop] == numbers[loopOther])
lottCount++;
}
if (userNumbers[loop] == bonusBall)
{
bonus = true;
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}
}
System.out.println("You have matched " + lottCount + " numbers");
The ouput looks like this:
15
16
17
18
19
43
You have not won at this time
You have not won at this time
You have not won at this time
You have not won at this time
You have not won at this time
You have matched 1 numbers the bonus ball43
You have matched 1 numbers
I only want the program to inform me of each condition once. can anyone help me with this? Thanks in advance
for (int loop = 0; loop <numbers.length; loop++ )
{
for (int loopOther = 0; loopOther < SIZE; loopOther++)
{
if (userNumbers[loop] == numbers[loopOther])
lottCount++;
}
if (userNumbers[loop] == bonusBall)
{
bonus = true;
}
}
if (bonus)
{
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}
Or shorter:
for (int number : numbers)
{
for (int userNumber : userNumbers)
{
if (userNumber == number)
lottCount++;
}
if (userNumber == bonusBall)
{
bonus = true;
}
}
if (bonus)
{
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball" + bonusBall);
}
else
{
System.out.println("You have not won at this time");
}