Infinite loops while validating input - java

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.

Related

How to update the variable secondPrice to the third else arguement?

while (true){
int secondPrice = 0;
String bid = scanner.nextLine();;
if (bid.isEmpty()){
System.out.println("The item " + auction.get(i).getName() + " was sold for " + secondPrice);
break;
}
if (Integer.valueOf(bid) <= auction.get(i).getPrice()){
System.out.println("Cannot bid lower than or equal to the amount given.");
System.out.println("Any bidders?");
}
else {
secondPrice += Integer.valueOf(bid) + 1;
auction.get(i).setPrice(Integer.valueOf(bid));
System.out.println("Price is now at " + Integer.valueOf(bid) + ". Any other bidders?");
}
}
When I run this, and I put some numbers on the scanner to raise the price, and when printing out secondPrice it's always 0, the same from the top.
it is because secondPrice is being re-initialized every time, try declaring it before the while loop. A simple way to program the second bidding system you proposed, you would have a variable storing each bid, then set the highest bid equal to the second highest bid + .01 before the payment is calculated

The program doesn't end when the timer ends until you give an input

I had some free time and I decided to make a program that could give me math questions using Java Eclipse. Whenever the timer ends during it though, the while loop doesn't end until you give one last input. I know that it is because of the while loop, but I don't know how to end it.
import java.util.Random;
import java.util.Scanner;
public class math_questioner_4 {
public static void main(String[] args) {
int firstnumber,secondnumber,operation,answer,answerinput,correctcount = 0,incorrectcount = 0, time, difficulty, max = 0, mixedop;
Scanner input;
System.out.println("What do you want the operation to be? 1 = addition 2 = subtraction 3 = multiplication 4 = division 5 = mixed");
input = new Scanner(System.in);
operation = input.nextInt();
// There is around 30 lines that don't relate to the question here
if (operation == 1) {
long endTime = System.currentTimeMillis() + (time*1000);
while (System.currentTimeMillis() < endTime) {
Random rand = new Random();
firstnumber = rand.nextInt(max) + 1;
secondnumber = rand.nextInt(max) + 1;
answer = firstnumber + secondnumber;
System.out.println("What is " + firstnumber + " + " + secondnumber + "?");
answerinput = input.nextInt();
if (answerinput == answer) {
System.out.println("Correct!");
correctcount++;
} else {
System.out.println("Sorry, " + firstnumber + " + " + secondnumber + " is " + answer + ".");
incorrectcount++;
}
}
// Another 140 lines here that don't matter either, just some operations
if (time == 1) {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " second!");
} else {
System.out.println("You got " + correctcount + " questions correct and " + incorrectcount + " wrong in " + time + " seconds!");
}
}
}
I know that it's because of the while loop that it won't end, but I don't know how. Also please don't yell at me. I'm a beginner that takes classes at my Chinese school, it's only my 9th week (I've been to nine classes) and this is random extra stuff. I get most of my answers from this website and I also have only learned to do things with integers. It's also my first question here.

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.

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

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.

Categories