I finished a beginner's game program and it works fine, except it's a bit slow when it prompts the user to play again. It is a do...while loop that goes around the entire main method. I want to make it so that the user only needs to type "1" and press enter ONCE rather than twice for the game to replay.
How can I fix this? Also, I'm not sure which part of my program I need to show (if needed), so if you need that, please let me know.
This should work.
if (correctc == 3 && correctp == 3){
System.out.println("\nUser wins! Colour was " + colchoice);
System.out.println("Press 1 to play again with a new combo.");
pagain = myInput.readLine(); // game starts with new combo or ends
}
// User tries guessing again
else{
System.out.println("\nEnter 1 to guess again.");
loop = myInput.readLine();
}
}while("1".equals(loop)); // user continues guessing the same combo
}while("1".equals(pagain)); // new game with new combo
The reason for this is readLine() waits for line to be terminated by "\n" (an enter in this case). You use it twice:
pagain = myInput.readLine();
and then
loop = myInput.readLine();
Isn't "pagain" supposed to be doin what your "loop" is doing? I beileve it is possible to use only one variable to steer both of these loops. For example, you ask to type in "1" to loop again the same set and type in "2" to try with a new set. Then you can get rid of the "loop" variable. It will go out of the inner do-while when it checks that you typed in "2".
Related
So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.
I want my program to check if the item entered is already in arrayList which is stored within my file ChessList.java, if so produce error and loop back to question else accept number and move on.
Reason being I only want one number to be selected in a row.
Say my program asks for Piece 1, row number and USER ENTERS 5
Then when program loops to piece 2, row number cannot accept 5 again and would produce error.
Therefore, two pieces cannot be contained within in the same row.
Any suggestions how I would go about this? thanks.
I haven't read your code because there's a lot of it, but it just sounds like you want something like
while(true){
int number = getNumber();
if(list.contains(number){
System.out.println("That number is already in the list. Try again");
else{
list.add(number);
break;
}
}
An alternative would be to store it as a Set, which does not store duplicates.
name = JOptionPane.showInputDialog("What is " + "your name? ");
How do I make this a do while loop so that if the user inputs a number instead of a string it will not move on till a letter is put in. Thanks
Before the loop make a boolean value set to true, and make it so the loop continues until you change the boolean to false. Only set the boolean to false when you get valid input.
You will of course have to check if the number is a int or a string, but exactly how you'd go about doing that will depend on if you want there to be no numbers at all in the string or if it's okay as long as there is at least one character. There are a lot of answers around about that so I'd just Google it.
I made a program that thinks of a number and you have to guess the number.
It is working well, but I got stuck.
First of all, you (the player) has 10 tries in a round. Every wrong guess subtracts 1 from the tries. If you reach 0 you lose.
The variable where the thing stores the randomized number looks like this:
int guess = Integer.parseInt(etGuess.getText().toString());
Of course I have an edittext field with the name etGuess.
So when the player enters the same number twice (for example: 5, then 5 again), the program subtracts 1 then again 1 (so 2) tries.
I'd like to know how can I get the previous value of the guess integer and check whether it was already guessed or not.
I think of something like this:
if ( previous_guess != guess )
Use a HashSet.
Here's how I would do this:
//Declare the variable outside of a function
HashSet<Integer> previousGuesses = new HashSet<Integer>();
//Check if it is already guessed
if (set.contains(guess)) {
//Alert the user that they can't use this.
}
//Adding a variable to it in a function:
set.add(guess);
Make sure to test if it contains before adding it or preforming any of the regular code.
Store all of your previous numbers in an array and then check the array then the player enters a new number.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to get my Do..While loop to display an error message to why it is re-asking for the user input again. This is my code for it:
do {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
}
// Loop until user input is equal to or less than the maximum floors
while( current_Floor > MAX_FLOORS );{
System.out.println("Please enter a floor which is less than 8");
}
The problem with this code is that the "Error" message which i've added appears after a correct user input has been entered, when I need it to display before the user input is added in. Any ideas?
Your formatting is all screwy, which is probably what's confusing you. The ; at the end of your while ends the do-while. The braces after that, containing the "error" statement, are just a static set of braces: they're not associated with your loop in any way.
If you format your code more legibly, it looks like this, which makes it clear that your "less than 8" message is placed incorrectly, and will always be printed, once you exit the loop.
do {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
} while( current_Floor > MAX_FLOORS );
{ // Useless braces!
System.out.println("Please enter a floor which is less than 8");
} // Useless braces!
If you want to loop until some condition is met while informing the user of "failed" iterations, the usual idiom is generally to loop forever, and then break when your condition is met:
while (true) {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
if (current_Floor <= MAX_FLOORS) {
break;
}
// This prints only if the user entered a bad number.
System.out.println("Please enter a floor which is less than 8");
}
Alternately, you can "extract" the first iteration of the loop, and then use a conventional while loop (or do-while if you're really committed to that structure for some reason) to ensure that the input is acceptable. Personally, I find the previous version a little cleaner, but that's really just down to personal preference and coding style.
// Initial input
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
// Loop until the input is acceptable
while (current_Floor > MAX_FLOORS) {
System.out.println("Please enter a floor which is less than 8");
current_Floor = in.nextInt();
}
As an aside, it's kind of nasty to be referring to MAX_FLOORS in the code, while hard-coding the magic number 8 into your error message: it would be better to use some string formatting to tell the user what the actual maximum floor number is.
System.out.println(String.format("Please enter a floor which is less than %d", MAX_FLOORS+1));
As another aside, your naming scheme is kind of weird: by convention, most variable names in Java should use camelCase, without underscores, e.g. currentFloor. Your MAX_FLOORS is okay though, since it seems to be a static/enum-like variable, which do conventionally use capslock with underscores.
Java do while syntax is as follows:
do {
//block of code to execute
} while([some boolean condition]);
Please look on Flow chart of a do-while loop:
And Read
That's not how do-while loops work in Java. I'd recommend sticking with a while loop since your initial pass is a little different from each subsequent one.
System.out.println("Please enter a floor which is less than 8");
current_Floor = in.nextInt();
while (current_Floor > MAX_FLOORS) {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
}
Here you prompt the user for an input. If it's invalid, you enter the loop where you display the error message and prompt them again. This will continue until the user behaves.
Your problem is that you are misusing the do-while loop.
do{
...STUFF...
}while( $CONDITION );
...MORE STUFF...
Works like this
do STUFF
calculate condition
if CONDITION is true, go to 1, if not go to 4
do MORE STUFF
In you case, STUFF is "ask the user for a floor", the condition is "is the floor the user selected greater than the max floor?", and MORE STUFF is "Ask the user to enter a floor less 8".
What you do is probably have the CONDITION be keep asking until a valid floor is selected, and have the check in an if statement inside the do-while loop.
The "do while" isn't the best type of loop to use here, because you need to check the condition in the middle of the repeated part, not at the end. It's possible to do this with "do while", but you end up checking the condition twice.
In order not to repeat code, there's a good alternative. The first line means "loop forever", but it will actually just loop until the "break" is encountered, which happens when the user enters correct input.
for(;;) {
System.out.println("\nPlease enter the floor you are on: ");
current_Floor = in.nextInt();
if (current_Floor <= MAX_FLOORS) {
break;
}
System.out.println("Please enter a floor which is less than 8");
}