How to end a loop when the value is 0? - java

How do I get a loop to go infintly but have it end when the value reaches 0? I want the process to end when the int money reaches 0. I am not that familiar with loops so sorry if this question is dumb.
System.out.println(list.get(0).array[3]);
for (int a = 10; a <= 1; a = a - money)
{
System.out.println("Enter in a vaule you want to bet out of $" + money + "");
String moneyvalue = Input.next();
int i = Integer.parseInt(moneyvalue);// i is the user input for
// amount of money they want
// to bet
int x = money;// total money
if (i > x)
{
System.out.println("Please enter an acceptable value from 1-" + x);
}
if (i <= x)
{
System.out.println("Which horse do you want to win, enter in 1-5");
String horsechoice = Input.next();
int randomhorse = (int) (Math.random() * 5 + 1);
int horsechoice1 = Integer.parseInt(horsechoice);
System.out.println(randomhorse);
if (horsechoice1 == randomhorse)
{
System.out.println("You win");
money = x + i;
System.out.println("You have $" + money + " remaining.");
}
else if (horsechoice1 > 5)
{
System.out.println("Sorry try again.");
}
else
{
System.out.println("You Lose");
money = x - i;
System.out.println("You have $" + money + " remaining.");
}
}
}

you can declare it in your for loop
for (int a = 10; a <=1, money > 0; a = a - money) {...

If( money ==0)
Break;
The break statement will get you out of the loop
You can place in last else where you are assigning money a new number
or you do this
for (int a = 10; a <=1, money > 0; a = a - money)

int money = 1000;//Initialize your value
while(money != 0){
//do some gambling
}

I'm not sure what you are doing with the for(a...) loop. I think you really just trying to construct the following loop:
while(money > 0)
{
// do some stuff!
}

int x = money;
while(x>0)
{
// your code here
}
or
int x;
for(;;)
{
x = money;
// your code here
// ...
//
if(x<=0) break;
}

Related

error msgs after second loop attempt

I'm working on another assignment and am stuck. First off, I realize I probably won't get the results I want from this code, but at the moment I can't run the code to even see how close or far away I am. I'm sure I'm missing something simple and hope that something will pop out to someone here so I can move past this point. My mother tongue is English but I'm living in Sweden and trying to learn code in a Swedish class so I added //for translations.
Again, I am working with very basic code so am not looking for an easy hack, more of just some insight to where I have gone wrong.
My assignment is to ask the user to enter 10 numbers, store those as an array. Then, offer the user 4 options to calculate those numbers and a 5th option to quit the program.
Here's what I have so far:
package inlämningsuppgift3;
import java.util.Scanner;
import java.util.Arrays;
public class Inlämningsuppgift3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal = 0;
int[] num = new int[10];
int sum = 0;
int min = 0;
int max = 0;
for (nr = 0; nr < 10; nr++) {
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr] = tal;
if (nr == 0) { //first number
min = tal;
max = tal;
}
else { // All other numbers
if (tal > max) { max = tal; }
if (tal < min) { min = tal; }
}
sum = sum + tal;
}
{
// What would you like to do?
System.out.println("Välj vad du vill göra?");
// Show largest number
System.out.println("1: Visa storsta talet.");
// Show smallest number
System.out.println("2: Visa minsta talet.");
// Show average
System.out.println("3: Visa medeltalet.");
// Show all numbers
System.out.println("4: Visa alla inmatade tal.");
// Quit
System.out.println("5: Avsluta");
}
do {
int k = input.nextInt();
if (k == 1) {
// Largest number is:
System.out.println("Storsta talet är: " + max);
}
else if (k == 2) {
// Smallest number is:
System.out.println("Minsta talet är: " + min);
}
else if (k == 3) {
// Average number is:
System.out.println("Medeltalet är: " + sum/10);
}
else if (k == 4) {
// All the entered numbers:
System.out.println("Alla tal: " + num[10] + ", ");
}
else if (k==5) {
// Goodbye
System.out.println("Hej då!");
break;
}
else {
System.out.println("Felaktigt, prova igen.");
// Unrecognized, try again.
}
while (k<5);
}
}
}
I'm getting error on the last 3 } and I'm not sure why. Are they in the wrong place? I've tried moving them around, I've tried deleting them (obviously, didn't help either) I tried changes to my {} placement above in the code and just haven't found a way around this error. Thank you in advance for any input!
java do-while syntax is:
do {
// Statements
}while(Boolean_expression);
so, change it to:
int k = 0;
do {
k = input.nextInt();
if (k == 1) {
System.out.println("Storsta talet är: " + max);
} else if (k == 2) {
System.out.println("Minsta talet är: " + min);
} else if (k == 3) {
System.out.println("Medeltalet är: " + sum / 10);
} else if (k == 4) {
System.out.println("Alla tal: " + num[10] + ", ");
} else if (k == 5) {
System.out.println("Hej då!");//good bye
break;
} else {
System.out.println("Felaktigt, prova igen.");
}
} while (k < 5) ;
and after while line must be two } now.
Hej Hej!
I made the modifications I think like you asked to make it 'just about work'
package Dunno;
import java.util.Scanner;
public class NumberCollector { //No special characters in source files,
//Can get transformed during deployment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int nr;
int antal =0;
int[] num = new int[10];
int sum = 0;
int min=0;
int max=0;
for (nr=0; nr<10; nr++)
{
System.out.println("Ange ett tal " + (nr+1) + " : ");
int tal = input.nextInt();
num[nr]=tal;
if(nr == 0) //first number
{
min=tal;
max=tal;
}
else //all other numbers
{
if(tal>max)max =tal;
if(tal<min) min=tal;
}
sum = sum + tal;
}
System.out.println("Välj vad du vill göra?");
//what would you like to do?
System.out.println("1: Visa storsta talet.");
//Show largest number
System.out.println("2: Visa minsta talet.");
//show smallest number
System.out.println("3: Visa medeltalet.");//show average
System.out.println("4: Visa alla inmatade tal.");
//show all numbers
System.out.println("5: Avsluta");//quit
while (true) //Moved the stop condition to start of the loop makes it easier to read logically.
{
int k = input.nextInt();
if (k==1)
{
System.out.println("Storsta talet är: " + max);
//largest number is:
}
else if (k==2)
{
System.out.println("Minsta talet är: " + min);
//smallest number is:
}
else if (k==3)
{
System.out.println("Medeltalet är: " + sum/10);
//average number is:
}
else if (k==4)
{
System.out.println("Alla tal: " + num[10] + ", ");
//all the entered numbers:
}
else if (k==5)
{
System.out.println("Hej då!");//good bye
break;
}
else
{
System.out.println("Felaktigt, prova igen.");
//unrecognized, try again.
}
};
}
}
I only had to move around some braces.
It seems to broadly do what you want? It throws an exception if you ask for result 4, I'll leave that to you :)
Maybe this will be a good starting point? Consider replacing the loop with a switch/case condition would be nicer to read and maintain?

How do I properly pass a scanner and an int into a function and return the integer value in java?

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

Creating 1 decimal place

So I am more or less completely done with this code that runs a guessing game. At the end it prints the total results for all games played. This includes total games, total guesses, avg guesses/game and the best score. I have it all worked out except i need the avg guesses/game to show 1 decimal place but the System.out.printf("Guesses/game = %.1f") isn't working and idk why
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
both totalGuesses and totalGames are integers, so when you divide them you get an integer, whereas %f needs a floating point number.
Instead cast one to a floating point number for floating point division:
totalGuesses/(double)totalGames
Try a decimal formatter if for some reason you're simply getting the wrong output:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is

How to get my program to start over when the user hits "y" on

So I've used System.out.print("Enter more test scores? (y/n): "); yet when I run it and all the scores are summarizes the user isn't given the chance to do it again here is my code. Do you guys think I may have put it in the wrong place.
public class TestScoreApp
{
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
outerLoop:
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
if (setNumber == counter)
{
break outerLoop;
}
//End of test scores while loop
}
userAnswer = sc.next();
}
}// end of do loop
while(userAnswer.compareTo("y") == 0 );
System.out.print("Enter more test scores? (y/n): ");
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
}
I dont know what exactly you want to do, if you want to ask if the user want to add more scores after the default scores (that user set on beggining) so this is the answer:
import java.text.NumberFormat;
import java.util.Scanner;
public class TestScoreApp {
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// declarations
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
// outerLoop:
// do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999) {
do { // put the loop condition below
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100) {
scoreCount += 1;
scoreTotal += testScore;
setNumber--;
} // Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
// if (setNumber == counter) {
// break outerLoop;
// }
if (setNumber == counter) { // test if the counter reached zero
System.out.print("Enter more test scores? (y/n): "); // ask if the user want to add more
userAnswer = new Scanner(System.in).next(); // read the input
if (userAnswer.toCharArray()[0] == 'y') { // if yes, do
setNumber += 1; // add +1 to setNumber, so user can add more one score
}
}
} while (setNumber > 0);
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" + "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n" + "Average score: "
+ averageScore + "\n"
// Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n" + "Min score: " + min + "\n";
System.out.println(message);
}
}
There are several modifications to be done in the program.
When you are asking user to enter the choice for inputting more, you should accept his/her choice in your userAnswer variable before closing off the do-while loop SO THAT THE USER CHOICE CAN BE CHECKED AFTER EACH ITERATION!
There is no need to break the OUTER-LOOP without checking user's input!
scoreCount & scoreTotal need to be initialised with 0 again in the beginning of the do-while loop.
The corrected program along with the imports needed :-
import java.text.NumberFormat;
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreCount = 0,scoreTotal = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
scoreCount=0;
scoreTotal=0;
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
System.out.print("Enter more test scores? (y/n): ");
userAnswer=sc.next(); // Single Error----Only corrected piece of code.
}while(userAnswer.compareTo("y") == 0 );
// end of do loop
}
}
You are asking the user:
System.out.print("Enter more test scores? (y/n): ");
after you exit from the while loop. This won't work. Just put this line exactly before:
userAnswer = sc.next();

Categories

Resources