Java Monopoly player select validation - java

I am programming a monopoly type game on java and am having a little trouble setting up the validation for the player select function. The user will have to chose between 2-4 players.
Below is my attempt at doing this utilizing an if else statement and a while loop.
I can't figure out the right way of implementing this and would appreciate any advice.
int numberPlayers = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter Number of players (2-4)");
if (scanner.nextInt() >= 2 && scanner.nextInt() <= 4) {
numberPlayers = scanner.nextInt();
System.out.println(numberPlayers + " players selected");
} else {
while (scanner.nextInt() < 2 || scanner.nextInt() > 4) {
System.out.println("Not a valid choice. Please enter Number of players (2-4)");
}
}

You can use a do-while loop to ask the user at least once for the player count and keep asking until the input is valid.
public int askForPlayers(Scanner scanner) {
int numberPlayers = 0;
do {
System.out.println("Please enter Number of players (2-4)");
numberPlayers = scanner.nextInt();
} while(numberPlayers < 2 || numberPlayers > 4);
return numberPlayers;
}
When you use a Scanner object, keep in mind that the user might enter something else that is not a number. You have to work with hasNextInt() and next() to deal with such a situation. Also, when you close the Scanner object, you are also closing the InputStream you used, see Close a Scanner linked to System.in.

Related

Implement/Substitute WHILE Loop with FOR Loop in number guessing game

So for my Java programming class one of the assesments is the following (a classic number guessing game):
Write a program that plays the Hi­Lo guessing game with
numbers. The program should pick a random number between 11 (inclusive) and 88 (exclusive), then
repeatedly prompt the user to guess the number. On each guess, report to the user that he or she is
correct or that the guess is high or low. Continue accepting guesses until the user guesses correctly or
choose to quit. Use a sentinel value to determine whether the user wants to quit. Count the number of
guesses and report that value when the user guesses correctly. At the end of each game (by quitting or
a correct guess), prompt to determine whether the user wants to play again. Continue playing games
until the user chooses to stop. You are required to utilise at least a while loop and a for loop correctly.
So far, the game is fully working, using WHILE and IF functions. But in order to get full marks on my solution, it requires me to use at least one FOR loop, but I'm struggling to do that.
import java.util.*;
public class Guessing {
public static void main (String[] args)
{
//Setting up the variables
final int MAX = 88;
final int MIN = 11;
int answer, guess = 1;
String another="Y";
//Intializing scanner and random
Scanner scan = new Scanner (System.in);
Random generator = new Random();
//play again loop
while (another.equalsIgnoreCase("Y"))
{
//Generate a random number between 11 and 88
answer = generator.nextInt(MAX-MIN)+11;
System.out.print ("Guess the number I picked between "+MIN+" and "
+ MAX + "!\n");
while(guess!=answer)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!");
break;}
}
}
//Asking player to play another game
System.out.println("Do you want to play another game?(Y|N)");
another = scan.next();
if (another.equalsIgnoreCase("N"))
System.out.println("Goodbye, thank you for playing");
}
}
}
So far, the program works. It correctly gives higher/lower advice, the current round stops when typing in 0 as a guess and you can start another round with Y/N. But Im struggling to substitute one of the functions/loops with a FOR loop.
You can substitute the central while loop with a for loop that you can also use to count the number of iterations
for(int i=0;;i++)
{
System.out.println("Enter your guess: ");
guess = scan.nextInt();
System.out.println(answer);
if (guess<answer && guess != 0)
System.out.println("Your guess was too low! (0 to exit) ");
else if (guess>answer)
System.out.println("Your guess was too high!(0 to exit) ");
else if (guess==0){
System.out.println("You excited the current round.");
break;}
else{
System.out.println("Your guess was correct!\n");
System.out.println("It took "+i+" guesses to get the answer");
break;}
}
}
This for loop is an infinite loop because it hasn't got the second argument. However your program will exit the for loop when the correct answer is given because of the break in the final else.
As the number of guesses is counted upwards, one may use the for loop on that.
Normally one would write for (int i = 0; i < n; ++i) { but here we want to know the loop counter after the for loop and have to declare it before:
int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses
There is no upper limit other than finding the answer or quiting.
All three parts in for (PARTA; PARTB; PARTC) are optional.

Java - while loop for scanner validation results in failed input

I am trying to add the following scanner validation as follows;
public void promptFilmRating() {
while (!filmScanner.hasNextInt()) {
System.out.println("Please enter a number instead of text.");
filmScanner.next();
}
while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
filmRatingOutOfFive = filmScanner.nextInt();
}
}
However when using the code that relates to the integer between value validation, repeated inputs are needed in order to record the original input and I am unsure on how to correct this, any advice would be fantastic.
I believe your problem is in while (filmScanner.nextInt() > 5 || filmScanner.nextInt() < 1) {.
Every call to filmScanner.nextInt() asks the stream for a new integer, so by calling .nextInt() twice in the while statement, you are asking for two numbers.
You might want to consider combining your two loops into one.
Example:
int myNum;
do {
myNumb = filmScanner.nextInt();
} while (myNum > 5 || myNum < 1);
Store the value that you are getting in a variable, and use that variable to perform the checks.
Here is an example:
private void promptFilmRating() {
Scanner filmScanner = new Scanner(System.in);
int filmRatingOutOfFive;
do{
System.out.println("Please enter your rating for the film:");
filmRatingOutOfFive = filmScanner.nextInt();
if(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1)
System.out.println("Your number is outside of the rating boundaries, enter a number between 1 and 5.");
}while(filmRatingOutOfFive > 5 || filmRatingOutOfFive < 1);
System.out.println("You rated this film: "+filmRatingOutOfFive+" out of 5");
}

Java Guessing game 'might not be initialized'

I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it? its correctNumber roughly line 16ish.
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
int correctNumber;
int guessTracker;
int guessLimit = 6; //the number of tries
int userInput;
Scanner in = new Scanner(System.in);
int game = 1;
boolean winTracker = false;
while (1 == game)
correctNumber = randomNumber.nextInt(1100); //computer generates a random number, max 100
userInput = 0;
guessTracker = 0;
System.out.println("Hello and welcome to this number guessing game. Please guess the number between 1 and 100 and I will help you by telling you if your guess is too high or low: ");
while (**correctNumber** != userInput && guessTracker < guessLimit){
userInput = in.nextInt();
guessTracker++;
if (userInput == correctNumber){
System.out.println("You have won the game! Your reward is a fact game: Did you know the first working camera was invented in 1816! "); //winner message, with a unlocked fact game
System.out.println("The correct number was " + correctNumber); //the correct number
System.out.println("It took a total of " + guessTracker + " guesses"); //number of guesses it took the user to guess the right number.
}
else if (userInput < correctNumber){
System.out.println("Your number is too low"); //displays that the users guess is too low
System.out.println("Please enter your next guess: "); //// user can now eneter their next guess
}
else if (userInput > correctNumber){
System.out.println("Your number is too high"); //displays that the users guess is too high
System.out.println("Please enter your next guess: "); // user can now eneter their next guess
}
if (correctNumber != userInput){
System.out.println("Sorry you have run out of guesses! The correct number was: " + correctNumber); // displays the correct number
}
}
}
}
You need to initialize correctNumber to a value.
This is not always the case, but think about this:
you call while(1 == game) which then initialized correctNumber to a random number, correctNumber = randomNumber.nextInt(1100) this would initialize correctNumber, but when the java compiler compiles your application it can't be sure that 1 == game is true. Therefore, when the compiler gets to the next loop while (**correctNumber** != userInput && guessTracker < guessLimit) your compiler sees that correctNumber has not been initialized even though it would be by the first loop.
In short, the compiler does not know whether a loop will be entered or not, therefore user3437460 is absoultely correct in saying that you need to initialize local scope variables, in this case int correctNumber = 0 will work perfectly for you.
I really need help with this. Im using BlueJ and it says 'might not be initialized'. How do i fix it?
Local scope variables need to be initialized (assigned an initial value) before use:
int correctNumber = 0
Same applies for your other variables.

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

How to check nextInt from Scanner without consuming the int itself

What I am attempting to do is verify user input of an integer between 0-136, while also making sure that the input IS in fact an integer. I can't figure out a good way to do so, as using nextInt in the conditional consumes the int, and you can't compare hasNextInt to integers. Any help would be greatly appreciated!
Here is my code:
public static int retrieveYearsBack() {
Scanner input = new Scanner(System.in);
//Retrieve yearsBack
System.out.println("How many years back would you like to search? (Enter only positive whole numbers less than 136)");
while (!input.hasNextInt([0-136]) {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
return input.nextInt();
}
I have also tried:
int myYears = -1;
int tempValue = 0;
while (!input.hasNextInt() || (myYears < 0 || myYears > 136)) {
if (input.hasNextInt())
tempValue = input.nextInt();
if (tempValue > 0 && tempValue < 136)
myYears = tempValue;
else {
System.out.println("Invalid entry. Please enter a positive whole number less than 136 only.");
input.next();
}
}
This try gets stuck in an infinite loop.
I believe that you do need the input.next() call despite what Vivin says. If you can't read an integer from the next line of stdin then you will end up in an infinite loop. Furthermore, you should handle the case where you run out of lines of stdin to process, which can happen where your application's input is from a pipe instead of an interactive session.
In a more verbose style, this might look something like:
public static int retrieveYearsBack() throws Exception
{
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
if (input.hasNextInt()) {
int years = input.nextInt();
if (0 <= years && years <= 136) {
return years;
}
} else {
input.next();
}
System.out.println("Invalid entry. Please enter a positive whole number less than 136.");
}
throw new Exception("Standard in was closed whilst awaiting a valid input from the user.");
}

Categories