I'm stuck with while loop on my random number guessing game - java

Want it to loop through everything until the user puts in the right number. When the user puts in wrong number it should say "type in a different number". When the user puts in the right number it should say "congrats you won". But until then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
If they guess it on 1 try they will be giving 500 dollar and second try 400 dollar and so on until 5 tries.
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "WELCOME TO GUESS GAME!" + "\nYou gonna guess a number between 1 and 20 " + "\nYou have 5 tries to guess the number! " + "\nYou gonna get more money on less tries, highest win are 500 dollar on one try! " + "\nHOPE YOU LIKE IT :)");
Random talet = new Random();
int secretnumber = talet.nextInt(20) + 1;
int tries = 0;
int money = 600;
String number;
int guess;
boolean win = false;
while (win == false) {
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
guess = Integer.parseInt(number);
tries++;
if (guess == secretnumber) {
win = true;
} else if (guess > secretnumber) {
JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
guess = Integer.parseInt(number);
} else if (guess < secretnumber) {
JOptionPane.showInputDialog("Your number is to high :(" + "\nType ina a lower number!");
guess= Integer.parseInt(number);
}
}
JOptionPane.showMessageDialog(null, "Congrats you won!" + "\nYour number was " + secretnumber + "\nit took you " + tries + "tries");
}
}

Adding an additional condition in while loop will work. If försök is the number of tries which can have maxium value of 5 (in your case) then condition should be :
while (win == false && försök<5) //if försök starts from 0
{
//code
if(win==true)
break;
försök++;
}
To display the message and score you can just check the value of försök after while loop:
if(försök==5)
{
// display this message: "you failed this mission! do you want to try again?"
score=0;
}
else
{
//display: "congrats you won"
score=(5-försök)*100;
}
Basically your code should be like this:
import javax.swing.*;
import java.util.Random;
class Projekt_1
{
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 500;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
if(tryCounter==0)
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
else
nummer = JOptionPane.showInputDialog("Enter no...");
guess = Integer.parseInt(nummer);
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " too small try a bigger one");
}
tryCounter++;
}
if(tryCounter==5){
JOptionPane.showMessageDialog(null,"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}
else
{
JOptionPane.showMessageDialog(null,"congrats you won"+"Your price is :" + (pengar - tryCounter * 100) + " Krones" );
}
}
}

you can have a control break while loop. which will be broken when the number of attempts become more then 5 OR when the correct number is inputted.See the below for reference
Scanner s = new Scanner(System.in);
int numOfTries = 0;
int input;
int correctNumn = 15;
while (true) {
input = s.nextInt();
if (input != correctNumn && numOfTries <= 5) {
numOfTries++;
if (numOfTries == 5) {
System.out.println("Game Over");
break;
}
continue;
} else if (input == correctNumn) {
System.out.println("corect ans");
break;
}
}

It is really hard to help you if you post all in your native language... but here is my answer...
the issue with your code was in the hole logi, you never use the variable tries(försök) and If the user guess a wrong number then you read the try again but instead you should start the logic of the while again....
anyways....
Example:
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 600;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
guess = Integer.parseInt(nummer);
tryCounter++;
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + "too small try a bigger one");
}
}
JOptionPane.showMessageDialog(null,
"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}

Related

Throws Exception when trying to break loop because a condition has been met

I am trying to figure out why I cannot get the loop to break if either "n" is input for playAgain or when the total is below $10. If you see how I can break the loop to run the gameOver function without having an exception thrown that would be a great help. I have noted in the code below that I am having trouble with. I am unsure why this exception is being thrown. If you are able to find out how to break the loop when total is less than 10 or when playAgain is false please let me know!
import java.util.Random;
import java.util.Scanner;
public class GameOfCrapsTester {
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
System.out.println("Welcome to the game of Craps");
System.out.println(" ");
System.out.println("The house has given you a starting balance of $500");
System.out.println("On each round, you will make a whole number wager.");
System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
System.out.println(" ");
System.out.println("You may keep playing until you decide to cash in, or");
System.out.println(" you can't cover the minimum wager.");
System.out.println("Good Luck!");
boolean win;
double wins = 0, numOfGames = 0;
int total = 500;
// Come out roll and set point value
int pointValue = 0;
boolean playAgain = true;
while (playAgain && total > 0)
{
System.out.println(" ");
System.out.println("Your balance is $" + total);
System.out.println(" ");
System.out.println("Place your bet: $");
// Get and check wager placed
int bet = in.nextInt();
while (bet > total || bet < 10)
{
if (bet < 10)
{
System.out.println("Bet must be larger than $10.");
}
System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
bet = in.nextInt();
}
int num = rollDice();
if ((num >= 4 && num <= 10 && num != 7) || num == 0)
{
pointValue = num;
System.out.println(" ");
System.out.println("Your point value is " + pointValue);
System.out.println(" ");
win = rollWithPoint(pointValue);
if (win)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else if (!win)
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
}
else if (num == 7 || num == 11)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
if (total <= 9) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
System.out.println("Keep playing (y/Y or n/N)? ");
in.nextLine();
String again = in.nextLine();
if (again.equalsIgnoreCase("y"))
{
playAgain = true;
}
else if (again.equalsIgnoreCase("n")) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
else
{
System.out.println("Invalid character input, try again:");
again = in.nextLine();
}
}// end of loop
gameOver(wins, numOfGames);
} // END of main
public static int rollDice() {
int dice1, dice2, total;
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
total = dice1 + dice2;
System.out.print("Your roll: ");
System.out.print("Dice1: " + dice1);
System.out.print(", Dice2: " + dice2);
System.out.println("; Roll Value: " + total);
return total;
} // END of rollDice
public static boolean rollWithPoint(int point) {
int total = rollDice();
boolean winner = false;
while(total != 7 && winner == false)
{
total = rollDice();
if (total == point)
{
winner = true;
}
else
{
winner = false;
}
}
return winner;
} // END of rollWithPoint
public static int lostGame(int bet, int total) {
System.out.println("Oh, I'm sorry, you lost.");
System.out.println(" ");
total = total - bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of lostGame
public static int wonGame(int bet, int total) {
System.out.println("A winner!");
System.out.println(" ");
total = total + bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of wonGame
public static void gameOver(double win, double tot) {
double winPercent = (win / tot) * 100;
System.out.println(" ");
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
System.out.println(" ");
System.out.println("Seems you lost your shirt; better luck next time.");
System.out.println("Have a nice day! Hope to see you soon!");
} // END of gameOver
} // END of GameOfCraps
There is no error when you change this (without using String.format()):
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
To this:
System.out.println("Based on your play, the probability of winning is " + winPercent + "%.");
Example with a little bet (console):
Your balance is $11
Place your bet: $
10
Your roll: Dice1: 1, Dice2: 2; Roll Value: 3
Oh, I'm sorry, you lost.
Your current balance: $1
Wins: 0.0 Number of games: 2.0
Based on your play, the probability of winning is 0.0%.
Seems you lost your shirt; better luck next time.
Have a nice day! Hope to see you soon!
I cannot get the loop to break if either "n" is input for playAgain or
when the total is below $10.
It works fine too. If I put a bet below 10 it asks me to put another bit. What

Palindromic numbers in Java

I write program to solve several problems with numbers. My program should:
Welcome users;
Display the instructions;
Ask for a request;
Terminate the program if a user enters zero;
List item
If a number is not natural, print an error message;
Print the properties of the natural number;
Continue execution from step 3, after the request has been processed.
I got an error:
The program should continue to work till the user enter 0.
Here is my code:
package numbers;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number >= 0) {
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
} else {
System.out.println("The first parameter should be a natural number or zero.");
}
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}
You are just a loop away from getting the desired output, below is the code with comments to understand properly. Also, I have commented the code which you wrote but I removed from there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// System.out.println("Welcome to Amazing Numbers!\n" +
// "\n" +
// "Supported requests:\n" +
// "- enter a natural number to know its properties;\n" +
// "- enter 0 to exit.\n" +
// "\n" +
// "Enter a request:");
// int number = scanner.nextInt();
//-------------------------------------------------------------
while (true)// added an infinite while loop, in order to display and take input continuously
{
System.out.println("Welcome to Amazing Numbers!\n" +
"\n" +
"Supported requests:\n" +
"- enter a natural number to know its properties;\n" +
"- enter 0 to exit.\n" +
"\n" +
"Enter a request:");
int number = scanner.nextInt();
if (number == 0)// checks for the number to be zero or not.
{
break; // jump statement, breaks out of the loop.
}
if (number > 0) {// if entered number is greater than zero,
System.out.println("Properties of " + number);
System.out.println("\t even: " + (number % 2 == 0));
System.out.println("\t odd: " + (number % 2 != 0));
System.out.println("\t buzz: " + checkBuzzNumber(number));
System.out.println("\t duck: " + checkDuckNumber(number));
System.out.println("\t palindromic: " + checkPalindromicNumber(number));
System.out.println();// for a new line
}
else // if number is less than zero,
{
System.out.println("The first parameter should be a natural number or zero.\n");
}
}
scanner.close();//good practice to close the scanner.
//____________________________________________________________
// if (number >= 0) {
// System.out.println("Properties of " + number);
// System.out.println("\t even: " + (number % 2 == 0));
// System.out.println("\t odd: " + (number % 2 != 0));
// System.out.println("\t buzz: " + checkBuzzNumber(number));
// System.out.println("\t duck: " + checkDuckNumber(number));
// System.out.println("\t palindromic: " + checkPalindromicNumber(number));
// } else {
// System.out.println("The first parameter should be a natural number or zero.");
// }
}
public static boolean checkBuzzNumber(int number) {
return number % 7 == 0 || String.valueOf(number).endsWith("7");
}
public static boolean checkDuckNumber(int number) {
String num = String.valueOf(number);
boolean flag = false;
if (num.startsWith("0")) {
return false;
} else {
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) == '0') {
flag = true;
break;
}
}
return flag;
}
}
public static boolean checkPalindromicNumber(int number) {
int rem, rev = 0, temp;
temp = number;
while (number != 0) {
rem = number % 10;
rev = rev * 10 + rem;
number = number / 10;
}
if (temp == rev)
return true;
else
return false;
}
}

How to fix NoSuchElementExeption in Java [duplicate]

This question already has answers here:
Why is this code getting a Java NoSuchElement exception?
(3 answers)
Closed 5 years ago.
I've made a simple game with 2 classes. It uses a scanner and when I try it it says java.util.NoSuchElementExeption. It also says the errors are on row 19 in RNGlog and 24 in RNG. Please help
First class: RNG
public class RNG {
public static void main(String[] args) {
RNGlog log = new RNGlog();
int max = log.max();
int min = log.min();
double counter = 3;
//Variables outside of loop
System.out.println("Write a number between " + max + " and " + min + ".");
System.out.println("If your number is higher than " + max + ", it will be " + max + ". Vice versa for " + min + ".");
System.out.println("If your number is higher than the random number, you win credits!");
System.out.println("You start with 2 credits.");
System.out.println("You lose if you hit 0 credits. Good luck!");
//Introduction
while(counter > 0) {
//Loop start
double r = Math.random() * 10;
float in = log.getIn(); //Error here
//Random number generator, input
double credit = 6 - in;
//Credit Win generator
if(in > r) {
counter = counter + credit;
//Counter refresh
System.out.println("Great job! The number was " + r + ".");
System.out.println("You won " + credit + " credits. Nice.");
System.out.println("Credit counter:" + counter + ".");
//Winning messages
}
else {
counter = counter - 1;
//Counter refresh
System.out.println("Nearly, n00b! It was " + r + ", how did u no realize.");
System.out.println("You lost 1 credits!");
System.out.println("Credit counter:" + counter + ".");
//Losing messages
}
if(counter <= 0) {
System.out.println("Game over! Better luck next time.");
//Game ender
}
}
}
}
Second class: RNGlog
import java.util.Scanner;
public class RNGlog {
int max() {
int max = 6;
return max;
}
int min() {
int min = 0;
return min;
}
float getIn() {
Scanner scan = new Scanner(System.in);
float imp = scan.nextFloat(); //Error here
if(imp < min()) {
imp = min();
}
//Stops number lower than 0
if(imp > max()) {
imp = max();
}
//Stops numbers higher than 6
scan.close();
return imp;
}
}
Would be really apriciated if someone could help!
NoSuchElementException : if the input is exhausted
you must test before with scanner.hasNext()
and if (scan.hasNextFloat())

Encountering Error with Pig Code

My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.

Java Unexpected Programming Result

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}
I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Categories