My guessing game takes either 5, 10, or 20 guesses from a user and they are supposed to try to guess a random number chosen by the computer. Everything in my code is working except this: when the code asks the user whether they want 5, 10, or 20 guesses, if the user were to enter 15, for example, which is not one of the options, it goes on and starts asking for their guesses. I need some type of validation that will make sure they enter one of the options. I'm not sure where or how to include this in the correct way since I am new to programming. I've tried several different ways but get errors for all. What I need is if the user puts a number that is not one of the options, it should just ask them again until they input one of the options. Can someone show me how I should do this?
First of all if (answer.length() ==3) makes no sense.
Maybe you meant:
if(answer.equals("yes"))
Besides, to accomplish what you want I would use a Set containing the valid guesses numbers. It is scalable and makes much more sense than checking against multiple values in an if clause. It will look like this:
Set<Integer> validNumberOfGuesses = new HashSet<Integer>(Arrays.asList(5, 10, 20));
int numberOfGuesses = scan.nextInt();
while (!validNumberOfGuesses.contains(numberOfGuesses)) {
/* ask again */
System.out.println(numberOfGuesses + " is not a valid number of guesses, please try again");
numberOfGuesses = scan.nextInt();
}
Take input from the user inside a loop. For example:
System.out.print("How many guesses would you like? (5, 10, 20)");
do {
int numberOfGuesses = scan.nextInt();
//on correct guess, break out of the loop
if(numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20)
break;
System.out.print("Please enter a guess having one of these values (5, 10, 20)");
} while (true);
Unless the user, enters one of the three values, he/she will kept being prompted to enter a correct guess value.
Java has the continue keyword that jumps to start of the current loop when run. See The Continue Statement documentation.
Once you have your user input you can do something like
if (numberOfGuesses != 5 && numberOfGuesses != 10 && numberOfGuesses != 20) {
continue; // jumps to start of while loop block, without running conditional
}
When you receive the "numberOfGuesses" you should check the value of that number before moving on. Otherwise you just move on in your code because you don't actually validate the number.
It may be a good idea to creat a function that returns a boolean value and then you can check the number there.
boolean isValidOption(int number)
In the function you want to perform some comparison and validate. Since you have three options you can opt for something like
if (number == 5 || ... )
You can consider how you'll verify the value as there are many ways. Just compare with valid numbers you know you want, you can do some if statements, or place the numbers in an array and compare the value while iterating through the array, and so on. Hope that helps you get started and happy coding!
Edit: Lastly I should have mentioned, but you need to consider the flow of your code. A loop of somesort like while(!isValidOption()) for your check should be use. Loop around the instructions until the user enters a valid option. You need to consider order of operations here in your code and understand the computer doesn't think for you. It does what you tell it, so understand what you are trying to tell it here. I want to step into my game, if and only if, the condition of isValidOption is met for example.
What you need to do is to stay in the loop until you get input that satisfy your demands for example you can use the following function
private int getNumberOfGuesses(Scanner scan) {
int numberOfGuesses;
boolean numberOfGuesesIsValid;
do {
System.out.println("How many guesses would you like? (5, 10, 20)");
numberOfGuesses = scan.nextInt();
numberOfGuesesIsValid = numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20;
if (!numberOfGuesesIsValid) {
System.out.print("Wrong option !!!");
}
} while (!numberOfGuesesIsValid);
return numberOfGuesses;
}
you can write your code inside a loop to make sure the value is either 5,10 or 20
while(numberOfGuesses!=5||numberOfGuesses!=10||numberOfGuesses=!20);
and the condition if(answer.length()==3 can cause errors. it means it will work every time the input is of length 3,even "noo"
Related
I apologize if this question is uber-simplistic, but I'm still in the early stages of learning Java. I have an example program that calls other methods within the class, and I'm not totally following a few of the elements - hoping someone can clarify. It's a simply random number guessing game and it works fine, but I want to better understand some components. Specifically:
There is a boolean variable (validInput) that is declared but never appears to be used anywhere in the methods
There are 2 methods (askForAnotherRound and getGuess) with a 'while' loop that just has 'true' as the variable(?) - i.e. "while (true)."
This code is directly from the example in the book and, again, it works. I just want to better understand those 2 elements above. (I think the validInput variable is not useful as when I 'comment out' that line the code still executes). I'm curious, though, about the "while (true)" element. There is an option to set, in the askForAnotherRound, to set the return value to false (ending the program). Are boolean methods defaulted to 'true' when they are first executed/called?
Again...understand this is probably a super-simple question for most folks on here, but as a newb I just want to understand this as best I can...
Thanks!!!
// Replicates the number guessing game using 4 separate methods.
import java.util.Scanner;
public class GuessingGameMethod2
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Let's play a guessing game!");
do
{
playARound();
}while (askForAnotherRound());
System.out.println("Thanks for playing!");
}
public static void playARound()
{
boolean validInput;
int number, guess;
String answer;
//Pick a Random Number
number = getRandomNumber();
//Get a guess
System.out.println("\nI'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = getGuess();
//Check the guess
if (guess == number)
System.out.println("You're right!");
else
System.out.println("You're wrong! The number was " + number + ".");
}
public static int getRandomNumber()
{
return (int)(Math.random() * 10) + 1;
}
public static int getGuess()
{
while (true)
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
System.out.print("I said, between 1 and 10. Try again");
}
else
return guess;
}
}
public static boolean askForAnotherRound()
{
while (true)
{
String answer;
System.out.print("\nPlay again? Y or N: ");
answer = sc.next();
if (answer.equalsIgnoreCase("Y"))
return true;
else if (answer.equalsIgnoreCase("N"))
return false;
}
}
}
I don't see boolean validInput being used either. But if it were to be used somewhere it would probably be to check that you guess satisfies 1 <= guess <= 10.
When it comes to askForAnotherRound and getGuess here's what you should know:
while(true) is always executed. One way you can get out of the while loop is if you use the break statement or if the loop is in a function you can return something. The method askForAnotherRound() will always return either true or false. Depending on the returned value of askForAnotherRound() you will either play another round or not. Note that when you have
`do{
...
someActions()
...
}while(booleanValue)`
someActions() will be executed at least once before it checks for the value of booleanValue which, if it turns out false you'll exit out of the do/while loop. Boolean methods do not default to anything, you have to give them a value.
Hope this helps! I'm also in the process of learning Java right now, so good luck!
As I see you're absolutely true about validInput - it isn't used. May be it will be used in the following chapters.
As for askForAnotherRound() - no, boolean methods don't evalute to true, by default. Even more, Java compiler throw an error if it find a method which does not return value and finish it execution in some cases.
while(true) - it's infinite loop, so it will be executed untill some instruction which interrupts loop, in general it's return statement.
askForAnotherRound() do the following:
- asks user if he/she want to play again
- returns true if user input "Y"
- returns false if user input "Y"
- asks again in all other cases(so it doesn't finish execution) and etc.
Hope it'll help
The validInput is indeed worthless.
The infinite loops are required to read from the console to get a valid input. e.g
while (true)
//start infinite loop
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
//continue the loop the input is not between 1-10
System.out.print("I said, between 1 and 10. Try again");
}
else
//break out of infinite loop, valid int
return guess;
}
If we take this method without the infinite loop, and i recommend trying this, it will simply return the value read even if it was not valid.
For example.
return sc.nextInt();
will allow any int returned, if we returned anything outside of the bounds in the current impl it would loop again until you enter a value between 1-10
The same is also true for ask for next round, its looping until a valid input is given.
I would bet the next exercises will use the validInput var as both these methods loop until a valid input is given.
You are right about validInput. It is not used. And probably missed after some code change. Should be removed.
while(true) - true is not variable but a boolean constant. It will basically make program run for ever in this case unless somebody kills program. Another alternative would have been to use break to exit out of loop on some condition.
"If a player's playerID ends in 00 to 49, this person is on the “lucky list”; however if the playID ends in 50 to 99, this person is on the “normal list”."
//Players ID, is what i have so far
System.out.println("Please enter the player’s ID (8 digits): ");
int playerId = input.nextInt();
//When i use if else statements i can select for certain cases. for example
if (playerId % 50)
normalList;
if (playerId % 3)
luckyList;
These are two example that i can think of. I assume there is a shorter and more logical way to do this but i dont have a clue how.
Be more clear on what normal list; and what luckyList; are. You say lists, so I am assuming you are using array or java.util.ArrayList to store your objects.
What I would do is to the effect of this:
`//Players ID, is what you have so far.
int playerID;
System.out.println("Please enter the player’s ID (8 digits): ");
playerID=input.nextInt();
System.out.println("Please re-enter the player's ID(8 digits):");
String IDword=input.next(); //can also use nextLine here
//now what happens is I have made a string version and an int version of your ID. Now, using charAt, I can access the last two values.
if(IDword.charAt(IDword.length()-2)=='4')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='3')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='2')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='1')
{
LuckyList.add(playerID);
}
if(IDword.charAt(IDword.length()-2)=='0')
{
LuckyList.add(playerID);
}
else
normalList.add(playerID);`
This detects the second to last digit- if it is 4 or less, it adds to luckyList. Else, it will add to normalList.
You may just want to add something indicating that the data is always 8 digits (that just being if(IDword.size()==8) do the following.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}
I am having a heck of a time trying to figure out why I can't leave a loop. What I need to do is leave the loop if my Boolean, forward, is set to true. (The Boolean has been set to false above the while loop.
When I run the code snippet below I and enter a positive number I can only enter an unlimited amount a numbers. When I enter a negative number I get one prompt telling me that's not allowed and to try again. After than I am stuck in the similar situation above. It doesn't matter what I enter next it will just keep letting input over and over again.
{
while (forward == false)
if (n2 == 0)
{
System.out.println("Sorry, the 0 is not a valid entry for the second number, try again!");
n2 = in.nextInt();
}
else
{
forward = true;
}
}
You can get away with using no extra variables
n2 = in.nextInt();
while (input == 0){
System.out.println("Sorry, 0 is not valid input");
n2 = in.nextInt();
}
as the forward is a boolean, you can use it directly instead of compare
forward == false.
If you wanna use this variable (I will not go thru the path of the best way achieve your aim), you can do the follow:
while (!forward) {
if (n2 == 0) {
System.out.println("Sorry, the 0 is not a valid entry for the second number, try again!");
n2 = in.nextInt();
} else {
forward = true;
}
}
Do you have an outer while loop that makes you go back into your while loop? An efficient way to solve loop issues is to debug the code a line at a time.
If you are in Eclipse, set a breakpoint (a place where your program will pause) by clicking on the line number just before entering the while loop. Then run the program, and you will see the current line highlighted. Then move line by line by pressing F6 repeatedly. In the bottom pane you can also find the current values of variables.
Now if you inspect your code line by line you will have a better idea of what's going on.
I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.