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())
Related
How to add a roll dice method and a check guess method?
My code:
package oui;
import java.util.Scanner;
public class dicecalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int numGuess;
System.out.println("Enter the number the numer the dice will roll: ");
numGuess = kb.nextInt();
int dice1=(int)(Math.random()*6+1);
int dice2=(int)(Math.random()*6+1);
int sum = dice1 + dice2;
System.out.println("Roll: total = " + sum);
{
if (sum != numGuess) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
}
I need to have this assignment resubmitted because I forgot those things but I don't know how to add it. Please help. I already have tried for days.
Here's one possible basic layout. Replace the ??? with some code!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number the numer the dice will roll: ");
int numGuess = kb.nextInt();
int sum = sumOfTwoDiceRolls();
System.out.println("Roll: total = " + sum);
{
if (!checkGuess(numGuess, sum)) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
public static int sumOfTwoDiceRolls() {
return ??? ;
}
public static int singleDiceRoll() {
// Math.random() * (max - min + 1) + min
return (int)(Math.random() * (6 - 1 + 1) + 1);
}
public static boolean checkGuess(int guess, int numberToGuess) {
return ??? ;
}
}
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
This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I am working on a project for my college, so far code is working fine, except when a program tries to calculate the average all input, it always gives the wrong answer.
Ex:
Test input:
3
-4
5
12
-7
0 (to exit the loop)
Result ->
sum: 9
Counter: 5
Average = 1.0 ? It should be 1.8
If anyone could help, please give me some advice.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int counter = 0;
int intInput;
int intLargest;
int intSmallest;
int intEven = 0;
int intOdd = 0;
int intSum = 0;
String strMessage = "Enter a series of value (0 to quit)";
System.out.print(strMessage);
System.out.println();
System.out.print("Enter Integer value?" + "\n");
intInput = sc.nextInt();
intLargest = intInput;
if (intLargest == 0)
{
intLargest = 0;
}
else
{
intLargest = intInput;
}
/////////////////////////////////////////////////////////////
intSmallest = intInput;
if (intSmallest == 0)
{
intSmallest = 0;
}
else
{
intSmallest = intInput;
}
while(intInput != 0)
{
{
if (intInput > intLargest)
{
intLargest = intInput;
}//Get the largest value
else if (intInput < intSmallest)
{
intSmallest = intInput;
}//Get the smallest value
if ((intInput%2) == 0)
{
intEven++;
}//Get number of Even value
else if ((intInput%2) != 0)
{
intOdd++;
}//Get number of Odd value
}
intSum = intSum + intInput;
intInput = sc.nextInt();
counter++;
}
/********************************************/
double doubleAvg = 0;
if (counter > 0)
{
doubleAvg = intSum / counter;
}
/***************************************************/
System.out.println();
System.out.print("Smallest = " + intSmallest +"\n");
System.out.print("Largest = " + intLargest + "\n");
System.out.print("Total Entered = " + counter + "\n");
System.out.print("Even Number = " + intEven + "\n");
System.out.print("Odd Number = " + intOdd + "\n");
System.out.print("Average = " + doubleAvg + "\n");
System.out.print("SUM: " + intSum + "\n");
}
}
Both intSum and counter are declared as int. And in case of dividing int by int the result will also be int. So result of division is 1 and then it is converted to double and you get 1.0. To get correct result declare intSum as double.
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");
}
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.