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

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

Related

java: How Not to save values from the code when looping back again?

How do I not store values from the program when it loops back again. For example, if I plan to enter two families, first I will ask for the details of the first family and display their names, and then I want to use the same variables to collect the next family and display their names without having stored information from the previous family.
public static void main(String[] args) {
// TODO code application logic here
String ans;
String res;
double cont;
int cot;
String name;
String order = "";
do {
ans = JOptionPane.showInputDialog(null,"What is the name of the "
+ "family?" );
res = JOptionPane.showInputDialog(null, "How many member in the " + ans +
" family?");
cot = Integer.parseInt(res); // Converts res String to a number
for (int count = 1; count < cot; count ++) {
name = JOptionPane.showInputDialog(null, " Enter first name: " + count);
order += name + " " + ans + "\n";
}
JOptionPane.showMessageDialog(null, "Members of the " + ans
+ " Family" + "\n" + order);
cont = JOptionPane.showConfirmDialog(null, "Do you want to add another "
+ "family", "Membership", JOptionPane.YES_NO_OPTION);
}while (cont == JOptionPane.YES_OPTION);
if (cont == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null," Come Back Again");
}
}
}
Your order variable is a String that you are adding the names to. Just reset it at the beginning of the loop:
...
do {
order = "";
...

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.

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.

an array does not get a value

I have a problem with the following code
public static void SideBet(int numberDice,int bet,int money) {
System.out.println("You established a " + "\""+ "point" + "\"" + ". " + "Your " + "\""+ "point" + "\"" + " is " + numberDice + ". " + "You have to roll a(n) " + numberDice + " to win your bet, "+ bet +" chips." );
System.out.println();
System.out.println("You can put side bets for 4,5,6,8,9 or 10.");
SideBetChoice = Console.readLine("Would you like to make any side bets ? (Type " + "\""+ "Yes" + "\"" + " or "+ "\""+ "No" + "\"" + ", then hit Enter.)");
int s = 0;
int r = 0;
if (SideBetChoice.equals("Yes")) {
System.out.println("You can put as many side bets as you would like for the numbers 4,5,6,8,9 or 10.");
int SideBetNumber = Console.readInt("How many side bets would you like to make ? (Introduce a number, minimum 1, maximum 6.)");
int[] SBNArray = new int[SideBetNumber];
int[] sbArray = new int[SideBetNumber];
for (s = 0; s <= (SideBetNumber -1) ; s++) {
SBNArray[s] = Console.readInt("On which number would you like to put a side bet ?");
sbArray[s] = Console.readInt("Currently you have " + money + " chips, how much would you like to bet ?");
money = money - sbArray[s];
System.out.println("Thank you for your " +sbArray[s]+ " chip side bet on number " +SBNArray[s]+".");
System.out.println();
}
}
if (SideBetChoice.equals("No")) {
return;
}
sbArray and SBNArray does not get a value and it keeps crashing ...
Can anyone help me out and tell me what is wrong, why the 2 arrays do not get a value, therefor they are null ?
There is no readInt()-method in Console.
Also I'm not sure if you're using console correctly, it should look like this:
Console console = System.console();
console.readLine("Type something");
Just use readLine() and convert it to an int:
Console console = System.console();
String input = console.readLine("Type a number");
try
{
int myNumber = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("This ain't a number!");
}
Also please never use Capital Letters for Variables' Names or method-names, it's very confusing because you could think it would be a Class or a Type.
So please change the name of SBNArray and SideBetNumber, SideBetChoice etc. etc.
Only Constants should be written with only Capital Letters and Classes and Types start with Capital Letters.
EDIT:
Sorry, it seems that you're using BreezyGUI.Console, therefore there is a readInt()-method.
Could you give more information?
I'd like to know if the text of the readInt() is even displayed.

Categories