Two die simulator do-while-if-else-if error - java

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.

Related

How do I fix my looping for this Single Player Dice Game (4 - 4 sided die)? Issues with Scanner input not yielding correct outputs

// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)

How to call a variable FROM another method INSIDE the main the method to perform a math calculation

Maybe I'm just stupid (probably) but I have been struggling with this for LITERALLY the past five hours and I really can't figure it out. Nothing on this site / google seems to help me; everyone wants to know how to call a method that's defined in the main method in another method, but I am trying to do it the other way around. I am new to java, but I am aware that you can't directly call a variable from a method into another method. However, I have tried so many different iterations of trying to get the values and NOTHING is compiling and I get the same errors over and over again: "error: cannot find symbol" for all of my variables.
All I am trying to do is read a text file and print out what percentage of the words are of x length up to 13 and say how many of those words are in the document so like "Proportion of 1- letter words: .7% (2 words)" is printed out all the way to "Proportion of 13- letter words: 80.7% (7000 words)" (this is how the output is supposed to look, I know it's not pretty).
Anyway please help me because I am stuck and tearing my hair out.
import java.util.*;
import java.io.*;
public class FileReader
{
public static void main (String [] args)throws FileNotFoundException
{
WordCount();
WordLengthCount();
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
System.out.println("Proportion of 1-letter words: " + count1/count + "% (" + count1 + " words)");
System.out.println("Proportion of 2-letter words: " + count2/count + "% (" + count2 + " words)");
System.out.println("Proportion of 3-letter words: " + count3/count + "% (" + count3 + " words)");
System.out.println("Proportion of 4-letter words: " + count4/count + "% (" + count4 + " words)");
System.out.println("Proportion of 5-letter words: " + count5/count + "% (" + count5 + " words)");
System.out.println("Proportion of 6-letter words: " + count6/count + "% (" + count6 + " words)");
System.out.println("Proportion of 7-letter words: " + count7/count + "% (" + count7 + " words)");
System.out.println("Proportion of 8-letter words: " + count8/count + "% (" + count8 + " words)");
System.out.println("Proportion of 9-letter words: " + count9/count + "% (" + count9 + " words)");
System.out.println("Proportion of 10-letter words: " + count10/count + "% (" + count10 + " words)");
System.out.println("Proportion of 11-letter words: " + count11/count + "% (" + count11 + " words)");
System.out.println("Proportion of 12-letter words: " + count12/count + "% (" + count12 + " words)");
System.out.println("Proportion of 13-letter words: " + count13/count + "% (" + count13 + " words)");
}
public static int WordCount(int n)throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int countABC=0;
while(keyboard.hasNext())
{
keyboard.next();
countABC++;
}
return countABC;
}
public static int WordLengthCount(int n) throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11 = 0;
int count12 = 0;
int count13 = 0;
int blob = 0; // so that if statement runs
while(keyboard.hasNext())
{
if (keyboard.next().length() == 1)
{
count1++;
keyboard.next();
return count1;
}
else if (keyboard.next().length() == 2)
{
count2++;
keyboard.next();
return count2;
}
else if (keyboard.next().length() == 3)
{
count3++;
keyboard.next();
return count3;
}
else if (keyboard.next().length() == 4)
{
count4++;
keyboard.next();
return count4;
}
else if (keyboard.next().length() == 5)
{
count5++;
keyboard.next();
return count5;
}
else if (keyboard.next().length() == 6)
{
count6++;
keyboard.next();
return count6;
}
else if (keyboard.next().length() == 7)
{
count7++;
keyboard.next();
return count7;
}
else if (keyboard.next().length() == 8)
{
count8++;
keyboard.next();
return count8;
}
else if (keyboard.next().length() == 9)
{
count9++;
keyboard.next();
return count9;
}
else if (keyboard.next().length() == 10)
{
count10++;
keyboard.next();
return count10;
}
else if (keyboard.next().length() == 11)
{
count11++;
keyboard.next();
return count11;
}
else if (keyboard.next().length() == 12)
{
count12++;
keyboard.next();
return count12;
}
else if (keyboard.next().length() == 13)
{
count13++;
keyboard.next();
return count13;
}
} return blob;
}
}
thanks!
Make the variable static and call it from the main method
There are a couple of things wrong in your code, but the biggest one is that you are returning the count when you find a word that has a specific Length.
You may want to create a class (say Document) that has the attributes you listed as variables in WordLengthCount (int count1, int count2, etc). Since attributes should most often be private, I would suggest doing an increment count method.
Finally, your WordLengthCount, can call the increment count method for the right word type, and return the object that you have created.
Moreover, instead of creating 13 variables, I would recommend using an array instead
int[] wordCount= new int[13];
You're trying to access local variables of one function in some other function. This is not possible. As the name suggests, local variables are local to the block or function in which they are declared. If you want to globally access these variables, make them class-level variables, i.e. declare them inside the class body but outside of any other function. Also, if you want to access them from static methods without creating object of the class, make these variables static.

Infinite loops while validating input

I'm having an issue with input validation. I wrote a program in which two people are simulating a dice game. The actual game code is alright but I just don't know why I am having an infinite loop when I'm trying to run the program again. Basically, if the user input "Y" the program will run again, if they input "N", the program will end and if they enter anything other than Y or N, the prompt, "Would you like to play again?" Is the following code right or do I need to change it up a bit(I'm mainly referring to the input validation code)?
do{
System.out.print("Would you like to play again? (Y/N): ");
String command = input.next();
if(input.hasNextLine()){
if(command.equals("Y") || command.equals("y")){
die1 = rand.nextInt(6) + 1;
die2 = rand.nextInt(6) + 1;
die3 = rand.nextInt(6) + 1;
die4 = rand.nextInt(6) + 1;
sum = die1 + die2;
sum2 = die3 + die4;
System.out.printf("%s rolled a %d and %d for a total of %d. %n", name1, die1, die2, sum);
System.out.printf("%s rolled a %d and %d for a total of %d. %n", name2, die3, die4, sum2);
if(sum > sum2){
System.out.println(name1 + " " + "won!");
}
else if (sum2 > sum){
System.out.println(name2 + " " + "won!");
}
else if (sum == sum2){
System.out.println(name1 + " " + "and" + " " + name2 + " " + "tied!");
}
game = input.nextLine();
}
else if(command.equals("N") || command.equals("n")){
System.exit(1);
}
}
}while(!validInput);
}
}
Edit: I deleted the entire code and just insert the piece of code that was in question but it is correct...thanks again!
input is a Scanner object and will never equal YES or YES2 which are String objects. You need to use nextLine to read the next String and save that value into a variable such as response. Then you can compare response to YES and other strings.
do {
System.out.print("Would you like to play again? (Y/N): ");
String response = input.nextLine();
if (response.equalsIgnoreCase(YES)) {
die1 = rand.nextInt(6) + 1;
die2 = rand.nextInt(6) + 1;
die3 = rand.nextInt(6) + 1;
die4 = rand.nextInt(6) + 1;
sum = die1 + die2;
sum2 = die3 + die4;
System.out.printf("%s rolled a %d and %d for a total of %d. %n", name1, die1, die2, sum);
System.out.printf("%s rolled a %d and %d for a total of %d. %n", name2, die3, die4, sum2);
game = input.nextLine();
break;
} else if (response.equalsIgnoreCase(NO)) {
System.exit(1);
}
} while (validInput);
You don't have to get all fancy with a do-while loop, if your going to terminate the program through System.exit() you can just surround your program with a while (true) loop. Also don't see a need for a hasNextLine here. You could shorten up the input validation with an equalsIgnoreCase("y"). Also it's usually a good idea to declare your variables outside of the loop. (ie. String command; on the outside, command = "stuff" on the inside). I'm not sure how it will work in this particular case but a lot of times you'll run into errors trying to redeclare variables.
The problem with your loop though that i see is that you have no else clause that deals with input if the user enters in something other than "Y" or "N". You could an else clause at the end that terminates the program if this other input is entered, or you could simply use a continue; statement to start to program over again.

if/else statement inside of a while loop

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

Java Menu Using Do while loop keeps repeating

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.

Categories