I'm working on a program to play the game of Go Fish. Everything works except for the scan.next() after looping through once.
Well, sometimes it works and sometimes it doesn't. Here's the code:
System.out.println(compHand.showHand());
while (!(deck.isEmpty())) {
y = 0;
while (x == 1) {
System.out.println("\nYour hand:" + userHand.showHand()+ "\nYour turn. What number do you want to match?");
guess = scan.next();
if (compHand.checkHand(guess)) {
System.out.println("Darn...here you go.");
userHand.removeNum(guess);
compHand.removeNum(guess);
userHand.showHand();
uP++;
}
else {
System.out.println("Nope! Type '1' to go fish!");
y = scan.nextInt();
if (y == 1) {
userHand.goFish();
System.out.println(userHand.showHand());
}
y = 0;
}
guess = "";
x--;
}
while (x == 0) {
System.out.println("Do you have any " + compHand.ask() + "s?");
ans = scan.next();
if (!(ans.contains("go"))) {
System.out.println("Yay!");
userHand.removeNum(ans);
compHand.removeNum(ans);
cP++;
x++;
}
else {
System.out.println("Aww...darn.");
compHand.goFish();
x++;
}
}
System.out.println("Computer's points so far: " + cP + "\nYour points so far: " + uP + "\n");
}
}
So the first time it loops through to do the user's hand, it works. Then it works for the computer's turn, but if the computer has to go fish. When it loops back up to the user's hand it skips the guess = scan.next();.
I don't know what to do...
The problems comes from the buffer. You have to free it. To do so, put a scan.nextLine() just before the closing bracket of the loop and it will free the buffer. You will be able then to enter an input.
Related
int levelP1;
int levelP2;
do {
p1.startTurn(p1, d1);
p2.startTurn(p2, d1);
levelP1 = p1.getLevel();
levelP2 = p2.getLevel();
} while (levelP1 <= 10 || levelP2 <= 10);
if (levelP1 >= 10) {
System.out.println(p1.getName() + " hit LvL " + levelP1 + " and WON the game !");
} else if (levelP2 >= 10) {
System.out.println(p2.getName() + " hit LvL " + levelP2 + " and WON the game !");
}
I have this pieace of code which is not doing what it is intended...
the "startTurn()" method might or might not level up the player, depending of what happens inside of it...
I want it to exit the loop when either player hits level 10 or above... Cannot figured out how. please help
I want it to exit the loop when either player hits level 10 or above.
Use && instead of || :
while (levelP1 < 10 && levelP2 < 10);
In this way, when one of these two conditions is false, you exit.
I took an excerpt of my code that needs working on, I know its standard practice to post all of the code but I dont think its needed here.
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision = sob.next();
if(decision.equals("Y") || decision.equals("y")){
continue;
}else if(decision.equals("N") || decision.equals("n")){
break;
}
}
}
How how I change this statement to either accept a Y or N, as right now if I input anything bar them two character, it will continue as if I have pressed Y.
You should have an else case:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision = sob.next();
if(decision.equalsIgnoreCase("Y")){
continue;
}else if(decision.equalsIgnoreCase("N")){
break;
}
else
{
//whatever you want to happen if they don't enter either y or n
}
}
}
Maybe in the else have another loop that says please enter a valid input and keep looping until they give a valid input...
Here is how you can change your code to "insist" on the user to enter a Y or a N:
static void readYesOrNo(Scanner input) {
String str;
while (true) {
str = input.next();
if (str.equalsIgnoreCase("y")) {
return true;
}
if (str.equalsIgnoreCase("n")) {
return false;
}
System.out.println("Please enter Y or N");
}
}
I put this code into a static method so that you could reuse it in other places. Now you can use this method in your code like this:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
if (readYesOrNo(sob)) {
continue;
}
break;
}
You Can Try This:
if(playerValue > 10 && playerValue < 21){
while(true){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision=sob.next();
if(decision!=null && (decision.equalsIgnoreCase("y")||decision.equalsIgnoreCase("n"))){
break;
}
else{
System.out.println("please answer with Either y or n");
continue;
}
}//end of while loop
//put your code here
}
I need to add "You got it right in ... guesses!" but I'm not exactly sure how. Can someone please explain to me how to do this in java?
I would like it to display a println at the end saying how many tries it took for the user to get the number correct.
import java.util.*;
public class prog210c
{
public static void main()
{
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
if(guess < randomNum)
{
System.out.println("Higher--Try Again");
}
else if(guess > randomNum)
{
System.out.println("Lower--Try Again");
}
else if(guess == randomNum)
{
System.out.println("Correct!");
break;
}
else
{
System.out.println("Enter a number between 1 and 100");
}
}
//System.out.println("You got it right in " + + " guesses");
} //end main
} //end class
Just create some int variable to store your number of attempts in and increment it every time you read in a guess.
int attempts = 0;
System.out.println("I am thinking of a number between 1 and 100");
while (true) {
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
attempts++;
/**
* The rest of your loop code here.
*/
}
System.out.println("You got it right in " + attempts + " guesses");
The simplest way to do this is declared a counter integer, and in your logic increment it every time the user attempts.
int guessCounter = 0;
while(true) // Also do not use an infinite while loop, have an expression that can be terminated
{
...obtain input
if(guess < randomNum)
{
...
guessCounter++;
}
else if (guess > randomNum){
....
guessCounter++;
}
System.Out.println("The number of attempts " + guessCounter);
}
You could do this by creating a variable to store the number of tries, like an int, and then add one to the int every time the user guesses, by using variable++:
public static void main(){
Scanner sc = new Scanner(System.in);
Random rn = new Random();
int tries = 0;
int randomNum = rn.nextInt(90) + 10;
System.out.println("I am thinking of a number between 1 and 100");
while(true){
System.out.print("What do you think it is? ");
int guess = sc.nextInt();
//Rest of your code here
}
System.out.println("You got it right in " + tries + " guesses");
}
and if you want to go even above and beyond, you could make it so it says You got it right in 1 guess instead of it saying You got it right in 1 guesses, if the user gets the number correct on their first try. We can do this by using the ternary Java operator, which is pretty much a compact if-statement:
String s = (tries == 1 ? "guess" : "guesses");
What this is pretty much doing is: if this is true ? do this : else do this
Now we can change the You got it right in... part of your program to say guess instead of guesses if the user guesses the number on their first try:
String s = (tries == 1 ? "guess" : "guesses");
System.out.println("You got it right in " + tries + "" + s);
When I run this code, which is a menu with many different options. it consists of many loops. Some of which I have yet to make. But my issue arises when I have the user select "t" or the coin toss simulator. The loop begins but once the user enters the amount of coin flips say 4, it says 2.0 heads and 2.0 tails means 50.0% were heads
Type code letter for your choice: COIN TOSS SIMULATOR
Enter 0 to quit. How many tosses?
It shouldn't say type the letter for your choice: COIN TOSS SIMULATOR, enter 0 to quit. how many tosses?
Also when I enter 0 it says You have entered an invalid option. 't' is not a valid option. I want to Bring back the main menu!!!! what is going on????
public class toolBox {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
boolean properInput = false;
int usersInput;
while (!properInput) {
System.out.println("Enter seed value:");
if (myScanner.hasNextInt()) {
usersInput = myScanner.nextInt();
properInput = true;
Random randomSeed = new Random(usersInput);
String randomNumberList = "";
for (int i = 0; i < 10; i++) {
randomNumberList += randomSeed.nextInt(80) + " ";
}
} else
{
String helloWorld = myScanner.next();
System.out.println("You have not entered an integer. '" + helloWorld + "' is not an integer");
}
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{
Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
outer:
while (!usersSelection) {
{
System.out.print("" + "Type code letter for your choice: ");
}
if (anotherScanner.hasNext("q|Q")) {
c = anotherScanner.next();
usersSelection = true;
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
{
System.out.println("" + "COIN TOSS SIMULATOR" + "");
}
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
boolean headsOrTails;
float headsCount = 0;
float tailsCount = 0;
Scanner scanMan = new Scanner(System.in);
int numero = scanMan.nextInt();
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
headsOrTails = rand.nextBoolean();
if (headsOrTails == true) {
headsCount++;
} else {
tailsCount++;
}
}
System.out.println(headsCount + " heads and " + tailsCount + " tails means "
+ (headsCount / (headsCount + tailsCount) * 100 + "% were heads"));
}
}
if (anotherScanner.hasNext("g|G")) // if the user were to enter either case of g, the
// program will register both and initialize the
// grade estimator.
{
c = anotherScanner.next();
usersSelection = true;
}
if (anotherScanner.hasNext("c|C"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println("Welcome to the Color Challenge!");
}
else {
String zoom = anotherScanner.next();
System.out.println("You have entered an invalid option. '" + zoom + "' is not a valid option.");
}
}
}
}
Your question is not clear, but your title suggests to me you think there is an inner and outer loop.
You don't have an inner and an outer loop.
Your indentation was really messy, but when I cleaned it up and then deleted a lot of extra lines of code, the structure of the code became clear.
Notice the following:
1) You have two loops, one on top switched on !properInput, the lower one switched on !usersSelection. There is also a for loop, but it doesn't do anything related to the code flow you are asking about.
2) You have two identical labels, one outside an anonymous block of code (see my comment in the code below), and another inside the anonymous block. In this case it doesn't affect your question, but it is definitely a problem.
My guess is that your break outer line isn't working because you are breaking out of the lower while loop.
I suggest you try fragmenting your code into functions to make the structure clearer.
while (!properInput) {
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{ /* begin anonymous code block */
outer:
while (!usersSelection) {
if (anotherScanner.hasNext("q|Q")) {
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
System.out.println("Enter 0 to quit. How many tosses?");
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
}
}
}
}
I am creating a hangman game. Everything works fine, I have code ready to be used for failing the game and giving -1 to the guesses. Though when adding it to the else statement it gets duplicate equal to the length of the word and it also gives a guess—even though its right? I don't see what's wrong in the code? I believe it's my code when guessing wrong which is not placed right though I see no other way?
This is the code:
private class check implements ActionListener {
public void actionPerformed(ActionEvent ae) {
try {
// Grabs the letter from the guessField and converts it into a char
// which can be used to compare against the word.
guess = guessField.getText();
guessField.setText("");
char guess2 = guess.charAt(0);
// --------------------
// Here is the guessing logic but it's currently
// not working and you can not win since i haven't written code for
// it yet. it's not selecting all the letters. for Example if
// choosing A in a word such as Banana it only selects the first
// a--------------------------- //
String displaySecret = wordField.getText();
if (displaySecret.equals("")) {/* case for fist execution */
displaySecret = "";
for (int i = 0; i < random.length(); i++)
displaySecret += "_ ";
}
String newDisplaySecret = "";
for (int v = 0; v < random.length(); v++) {
if (guess2 == random.charAt(v)) {
newDisplaySecret += random.charAt(v); // newly guessed
// character
} else {
newDisplaySecret += displaySecret.charAt(v); // old state
guesses--;
statusLabel.setText("Guesses left: " + guesses);
missField.setText(missField.getText() + guess);
if (guesses <= 0) {
JOptionPane.showMessageDialog(null,
"Game over! The word was: " + random);
guessField.setEditable(false);
wordField.setText("");
missField.setText("");
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
}
}
}
displaySecret = new String(newDisplaySecret);
wordField.setText(displaySecret);
if (displaySecret.equals(random)) {
JOptionPane.showMessageDialog(null, "You Won! The Word was: "
+ random);
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
wordField.setText("");
missField.setText("");
guessField.setEditable(false);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
If randomis your Word, you iterate over each Character of it and then check whether each single character matches the guess you get for each character that doesn't match the guess a -1.
For Example: The Word is Bananaramaand you guess a nyour first and second matches will go to the else clause. then one time the if clause goes again, then the else and so on.
You have to
iterate over all characters, check whether they match or not
if a match occurs, replace the char and increase the counter
check if the counter of correct characters equals 0
if so, decrease the guesses
Some other tips: you should use .toLower() on your input and word string before comparsion to allow insensitivity for case
Some sample code:
int charsGuessedCorrectly;
for ( int i = 0; i < random.length( ); i++ )
{
if ( random.charAt( i ) == guess )
{
charsGuessedCorrectly++;
newDisplaySecret += random.charAt(v); // newly guessed
// character
}
}
if ( charsGuessedCorrectly == 0 )
{
newDisplaySecret += displaySecret.charAt(v); // old state
guesses--;
statusLabel.setText("Guesses left: " + guesses);
missField.setText(missField.getText() + guess);
if (guesses <= 0) {
JOptionPane.showMessageDialog(null,
"Game over! The word was: " + random);
guessField.setEditable(false);
wordField.setText("");
missField.setText("");
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
}
Here is what you need to check your word and generate "newDisplaySecret":
for (int v = 0; v < random.length(); v++) {
if (guess2 == random.charAt(v)) {
newDisplaySecret += random.charAt(v); // newly guessed
// character
} else {
newDisplaySecret += displaySecret.charAt(v);
}
Here is how you can determine whether the player guessed right or wrong:
if(newDisplaySecret.equals(displaySecret)){
guesses --;
}
This needs to be placed after your check word code. Your code seems to decrement guesses for each letter in the word random.
Update display:
displaySecret = new String(newDisplaySecret);
wordField.setText(displaySecret);
Now that you know what the current state of affairs is for this move you can decide if the person has won or lost or just needs to continue playing:
if(guesses <= 0){
/*place here instructions for loosing scenario*/
}else{
if(displaySecret.equals(random)) {
/*place here instructions for winning scenario*/
}
/*simply do nothing the game is neither lost or won*/
}
Hope this helps