Unable to access scanner on nested if condition [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
The expected output of the code is for a user to guess a randomly generated number between 0 to 100000, and for each guesses he pay $1.00, if the user guesses right he wins $1m, if not he is asked if he want a hint. each hint cost $2.00. so the code continues to run until the user quits the game or wins. the problem with my code is that after asking the user if he wants a hint or not the scanner input code doesn't run.
package com.company;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int guess, toguess;
String payOrQuit, yesOrNo;
double totalSpent = 0.0, hint, value;
boolean isWon = false, isQuit = false;
Random rand = new Random();
while (!isWon && !isQuit) {
toguess = rand.nextInt(1000000);
System.out.println("Want to win a million dollars?");
System.out.println("If so, guess the winning number (a number between 0 and 100000).");
System.out.print("Insert $1.00 and enter your number or 'q' to quit: ");
payOrQuit = input.nextLine();
if (payOrQuit.matches(".*\\d.*")) { // IF pays or quit
value = Double.parseDouble(payOrQuit);
System.out.println(toguess);
System.out.print("Guess a number: ");
guess = input.nextInt();
if (guess == toguess) { // IF 2 starts
System.out.println("YOU WIN!\nYou won $1000000!");
isWon = true;
} else {
totalSpent += value;
System.out.print("Sorry, good guess,Do you want me to give you a hint (y|n)?");
yesOrNo = input.nextLine();
if (yesOrNo.equals("y")) { // IF 3 starts
System.out.print("Insert $2.00 for the hint! : ");
hint = input.nextDouble();
totalSpent += hint;
if (guess > toguess) {
System.out.println("Guessed number too high");
} else {
System.out.println("Guessed number too low");
}
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF 3 ends
} // IF 2 ends
} else {
System.out.println("amount lost = " + totalSpent);
isQuit = true;
} // IF pays or quit ends//
}
}
}

The problem is because of input.nextInt() and input.nextDouble().
guess = input.nextInt();
Change it to
guess = Integer.parseInt(input.nextLine());
Similarly, also change
hint = input.nextDouble();
to
hint = Double.parseDouble(input.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.

Related

This program causes an infinite loop in console [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 19 days ago.
I'm new to Java, just started a couple days ago. I have this program wich does some cool checks on an input number, but for semplicity i just created a class TestToFixLoopIssue because loop is actually the issue im facing. When we choose to enter a number, we enter the if with choice == 1, so the Test class is called, does its things, and when we quit that "program" we get an infinite loop in the console. This does not happen if i just copy paste the Test code into the if (removing its Scanner). So i think its a problem related to the multiple Scanners, but i dont know how to fix it.
EDIT: i tryed adding s.next(); but this does not fix the issue, it just gives another error in console wich stops the program:
Exception in thread "main" java.util.NoSuchElementException
public class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("What do you want to do?");
System.out.println("1. Check a number");
System.out.println("2. What is this program about?");
System.out.println("3. Quit");
if (s.hasNextInt()) {
int choice = s.nextInt();
s.nextLine();
if (choice == 1) {
System.out.println(" ");
// NumberChecker nc1 = new NumberChecker();
// nc1.check();
TestToFixLoopIssue test1 = new TestToFixLoopIssue();
test1.check();
} else if (choice == 2) {
System.out.println(" ");
System.out.println("This program checks multiple properties of a number.");
} else if (choice == 3) {
exit = true;
System.out.println(" ");
System.out.println("Program closed!");
} else {
System.out.println(" ");
System.out.println("Invalid choice. Try again.");
}
} else {
System.out.println("Invalid input. Try again.");
}
}
s.close();
}
}
public class TestToFixLoopIssue {
public void check() {
Scanner scan = new Scanner(System.in);
boolean repeat = true;
while (repeat) {
System.out.print("Insert a number: ");
int number = scan.nextInt();
System.out.println(" ");
System.out.println("You inserted " + number);
System.out.println("Do you want to check another number?");
System.out.println("1. Yes");
System.out.println("2. No");
if (scan.nextInt() == 2) {
repeat = false;
}
}
scan.close();
}
}
I dont want the loop to generate, so the user can keep using the program. I tryed some methods of the Scanner but neither of them worked, i dont actually know whats the issue exacty, so... help!

How can I avoid my loop to take the previous answer of the user?

I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.

How to make the Guess Game start again. While loop Java

I'm practicing Java and i tried to make a guess game but i want the game to ask for input again when the user don't guess the number right. When i guess the number wrong the loop just continuous to guess numbers until the number is the right one and the game ends.
import java.util.*;
class GuessGame {
private Scanner userInput = new Scanner(System.in);
public GuessGame(){
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
}
int guessedNumber = 0;
public void gameStart(){
System.out.println("Guess a number: ");
boolean guessedRight = false;
boolean gameOn = true;
int userNumber = userInput.nextInt();
while(gameOn){
guessedNumber = userNumber;
int randomNumber = (int) (Math.random() * 10);
if(randomNumber == guessedNumber){
guessedRight = true;
}
if(guessedRight){
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("You won!!!");
System.out.println("Game Over!!!");
break;
}else{
System.out.println("You guessed " + guessedNumber);
System.out.println("The number is " + randomNumber);
System.out.println("Try again!!!");
}
}
}
}
The int userNumber = userInput.nextInt(); line is responsible for getting the number that the user entered from the input line. Moving this line inside the while loop will ask for a number each time the loop is ran (which is only once if the user guesses right the first time).
Just call the method from a loop:
public GuessGame(){
while(true) {
System.out.println("~~~Guess Game~~~");
System.out.println("~~~Guess a number between 0 and 9~~~");
gameStart();
}
}
This will simply restart the game as soon as the gameStart() method exists. (Which is when the user has guessed the right number)

Guessing Game - it won't loop

As part of our coursework myself and another person in my class have to make a Guessing Game where a random number is generated between 1 to 100 and the user has a maximum of 6 guesses to try and guess the number. I also have to create a "session" where the user can enter their name and it will store their results into a text file. I have got it working to a point where they can play the game and successfully input their name, but if you select the option that you want to play again, it says 'Process completed' and exits the program. Help would be greatly appreciated, here is what I have so far;
Code:
import java.util.Random; //importing the Random class
import java.util.Scanner; //importing the Scanner class
/* Author Laura Brown 28/02/2014 */
public class TheGuessingGame
{
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int TARGET = generator.nextInt(100) + 1; //establishes the target number
int guess;
int count = 0;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
}
You need to add another loop. Stylistically speaking, I would avoid using do...while loops, as they are difficult to read. I have included a while loop done the more traditional way to show you how blissfully sexy they are.
while(anotherFlag)
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do
{ //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else
{
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
}
The above won't work fully, you need to set anotherFlag to false if the user inputs 'no'. That should be a relatively simple exercise, but the above will get the program to loop over and over.
public static void main(String[] args)
{
Random generator = new Random(); //creates a random number between 1-100
int guess;
int count = 0;
int Target;
String userName;
String another = "y";
Boolean flag = false;
Boolean anotherFlag = true;
Scanner consoleIn = new Scanner(System.in); //creating a new Scanner object
Scanner name = new Scanner(System.in); //creating a new Scanner object
System.out.print("Hello! Please enter your name:\n"); //asking for user input
userName = name.nextLine();
System.out.print("Hello "+ userName+ ", and welcome to the game!\n");
while (another.equalsIgnoreCase("y")) // this will check if your user input "another"
{
TARGET = generator.nextInt(100) + 1; //establishes the target number
System.out.print("Can you guess what it is?\n");
do { //beginning the loop
guess = consoleIn.nextInt();
count++;
if (guess > TARGET)
System.out.print("Sorry - Your guess is too high \n");
else
if (guess < TARGET)
System.out.print("Sorry - Your guess is too low \n");
}
while(guess != TARGET && count < 6);
if(guess == TARGET) {
System.out.println("Congratulations! - You found it!");
System.out.println();
}
else {
System.out.println("Sorry - You have used all 6 guesses");
}
System.out.println();
System.out.println("Would you like to guess again? (yes/no)");
another = consoleIn.next();
consoleIn.nextLine();
}
}
}
Added in another loop to loop the whole gaming process. And brought down the random generating method to be inside the loop to regenerate a new number. Try it. Anyway I added another line consoleIn.nextLine(); after your user input to clear the carriage return buffer for .next() method.

How to reach a desired point in the code in java? [duplicate]

This question already has answers here:
How to repeat/loop/return to a class
(4 answers)
Closed 8 years ago.
I want to make a logic of getting grades. I proceed in a way of getting total marks as input from user using the Scanner class, then I'm validating marks if it is between 0 and 100(both inclusive).
Now if the marks are not in between this range, I print "Enter valid marks!!", and I want it to go to previous step and ask for the input from user again.
import java.util.Scanner;
class Performance
{
public static void main(String[] aa)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
}
// Now if this condition is true then I want the control to go again to line 7
// Please suggest me the way to Proceed
}
}
Please suggest the way to proceed with the modification in the above code.
See this link.
You want to do something like that:
do {
code line 1;
code line 2;
code line 3;
} while(yourCondition);
Now, if yourCondition is satisfied, the code will go to code line 1 again (will perform the code block between do and while).
Now, after you understand how it works, you can easily apply this to your task.
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
} else
break;
} while (true);
Try this:
boolean b = true;
while(b){
if(marks<0 || marks>100){
System.out.println("Enter valid marks!!");
marks= scnr.nextInt();
}
else{
b= false;
//Do something
}
}
8 int marks = scnr.nextInt();
9 while(marks<0 || marks>100)
10 {
11 System.out.println("Enter valid marks!!");
12 System.out.println("Enter the marks :");
13 marks = scnr.nextInt();
14 }
Thanks Guys for your help.
FInally i proceeded in the way as follows:
public static void main(String[] aaa)
{
int counter=0;
Scanner scnr = new Scanner(System.in);
int marks;
do
{
counter++;
System.out.println("Enter the marks :");
marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Marks entered are not valid");
if(counter>=3)
{
System.out.println("You have exceeded the maximum number of attempts!!");
System.exit(1);
}
else
System.out.println("Enter valid marks!!");
}
else
break;
} while(true);
}

Categories

Resources