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;
Related
I have a math quiz game I am making and I am not sure how to loop it, let's say 50 times. It ends after answering only 2 questions. I also want to add lives so after you get three questions wrong it ends the program. How am I able to do this?
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}else {
System.out.println("Wrong!");
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
System.out.println("You got " + correct + " correct answers.");
After the int correct = 0;
add a lives counter.
eg:
int lives =3;
then start a while loop
while(lives > 0){
reduce the lives if a question is incorrect (where you put "wrong!" message)
lives--;
at the end of the while loop (before no of correct answers is printed out)
remember to put the last }
This will keep looping till you lose your lives
A couple things:
-There are multiple java structures which allow you to loop. The main loops out there in any kind of programming language are for loop, while loop, and do-while loop (uncommon)
-You can create lives by defining a variable and checking it in every iteration (an iteration is each "run" through the code of a loop).
Your code after implementing this 2 things would look like this:
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int Number1 = (int)(20 * Math.random()) + 1;
int Number2 = (int)(20 * Math.random()) + 1;
int correct = 0;
int lives = 3;
//The for loop is read as: having i equal 25 and the variable lives, iterate if i is lower than 25 AND lives is higher than 0. After an iteration, add 1 to i;
for (int i=25, lives; i<25 && lives > 0; i++) {
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
} else {
System.out.println("Wrong!");
lives--;
}
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}else{
System.out.println("Wrong!");
lives--;
} //Forgot this bracket
} //Closes the for loop
System.out.println("You got " + correct + " correct answers.");
See if below example works as you intend. Here I have given the loop count as 5. So there will be 5 "addition" questions and 5 "multiplication" questions.
I'm printing the question number also. So, now the output is more clear.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int correct = 0;
for (int i = 0; i < 5; i++) {
int Number1 = (int) (20 * Math.random()) + 1;
int Number2 = (int) (20 * Math.random()) + 1;
System.out.println("Question " + (i*2+1));
System.out.print(Number1 + " + " + Number2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == Number1 + Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
System.out.println("Question " + (i*2+2));
System.out.print(Number1 + " * " + Number2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == Number1 * Number2) {
System.out.println("Correct!");
correct++;
}
else {
System.out.println("Wrong!");
}
System.out.println();
}
System.out.println("You got " + correct + " correct answers.");
}
}
I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!
I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.
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();
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;
}