Java - 2-Do-While Loops in a For Loop - java

I'm quite new to programming so excuse my basic and limited understanding. Essentially, I am creating a Memory Game for a school project. I want to do 2 do-while loops in a for loop that works like this: the user will be prompted to enter a 4 random letters which will be done in the first do-while loop and the second do-while loop will ask the user to re-input the phrase that they had initially entered.
So my first question is, why does only the first do-while execute? I'm assuming that the for loop executes the first-do-while and than repeats based on my parameters therefore the second one will never execute but, I'd appreciate any help understanding why, and reformatting my program accordingly perhaps.
My second question is that, I want to have a sort of score counter that nets the user 10 points for every correctly guessed letter in the correct sequence and deduct 10 for every incorrect character in the wrong sequence. How would I go about doing so, and what may I have to utilize to make this possible?
Lastly, I would appreciate if anyone could point towards a way of concealing the letters that the user inputs.
Any other suggestions to make my program more efficient would be greatly appreciated!
import java.util.Scanner;
import java.lang.String;
public class MemoryGame {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int choice;
System.out.println("This is a M E M O R Y G A M E");
System.out.println("Press '1' for instructions");
System.out.println("Press '2' to play");
choice = input.nextInt(); //Checks user selection and redirects
if (choice == 1) {
Instructions();
} else {
playGame();
}
input.close();
}
public static void Instructions() { //Instructions method
int choice;
Scanner input = new Scanner(System.in);
System.out.println("This is a memory game. Below are a few instructions on how to play as well as few hints, and tricks");
System.out.println("> Players wlll be given a input box to input a given number of letters or numbers depending on the stage level.");
System.out.println("> To progress and gain points, users must sucessfully recall the set phrase that they have inputted.");
System.out.println("> Based on the number of correct letters, users will gain points and progress through a set of levels that increase in difficulty.");
System.out.println("> Upon making 3 incorrect character selections users will be displayed a 'Game Over' screen from which they may:");
System.out.println("1. Head to the main menu");
System.out.println("2. View the instructions");
System.out.println("3. Play again");
System.out.println("If users successfully oomplete 5 stages with no errors, they will be prompted a challenge level in which more characters will be required");
System.out.println(" ");
System.out.println("1. Press '1' to return to play");
choice = input.nextInt();
if (choice == 1) {
playGame();
}
input.close(); //Closes input.
}
public static void playGame() {
int userNumbers1;
int userNumbers2;
String userLetters1;
String userLetters2;
int scorePlayer;
int livesPlayer = 3;
int stagePlayer = 4;
int stageGeneral = 1;
Scanner input = new Scanner(System.in);
System.out.println("This is the M E M O R Y G A M E");
System.out.println("Stage 1 initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
for (int i = 0; i <= 10; i++) {
do {
userLetters1 = input.nextLine();
userLetters1 = userLetters1.toLowerCase(); userLetters1.trim();
if (userLetters1.length()==stagePlayer) {
System.out.println (". . .!");
stagePlayer = stagePlayer + 2;
stageGeneral = stageGeneral + 1;
} else {
System.out.println("Please enter " + stagePlayer + " letters");
}
}
while ( userLetters1.length() != stagePlayer);
do {
userLetters2 = input.nextLine();
userLetters2 = userLetters2.toLowerCase(); userLetters2.trim();
if (userLetters2.length()==userLetters1.length() && userLetters2.equals (userLetters1)) {
System.out.println (". . .");
System.out.println ("Great job!");
System.out.println("Stage " + stageGeneral + " initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
} else {
System.out.println ("Please enter " + userLetters1.length() + "letters that were previously entered.");
}
}
while ( userLetters1.length() != userLetters2.length());
}
}
}

Don't assume. Debug instead. Look what happens line by line and determine the reason the first do lop never exits. It if exited I see no reason why the second one didn't execute.
For second question I'd enciurage to read String class documentation. All you need is to iterate through characters and react accordingly to results of copmarisions.
In console, to hide previous user input you could clear the screen like:
Runtime.getRuntime().exex("cls);

Related

infinite loop in a while statement

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From Scanner#hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}

How do I make it so that it stars over if the user inputs wrong number OR start over if user types in "1"

package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
How do I make the class start over when user input 1 OR if the Class can start over if User inputs wrong number from the start, many thanks
The "start over" logic based on some conditions is usually implemented with while and do/while loops.
First let's extract those conditions. We want to iterate again (start over) if:
The user's guess is wrong.
The user's guess is correct, but they input a number different than 1 when asked if they want to continue.
Since we want to run the program at least once, the natural approach would be with a do/while. This will run one iteration, then check against the conditions wanted.
Here's what it looks like:
private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}

Java Looping issue in Hangman program(Cant find)

I have the majority of my program finished, but now that I have most of the code it is tough to find the errors. I have multiple errors at the moment, but the main error I really need help with is that my program will loop the same guess over & over if it is correct. It is in an infinite loop, & I cannot find where it is. This has also brought to my attention that my program will go into negative guesses as it is supposed to end when it gets to 0. Some other errors that would be nice to get help with is 1) it shows a correct guess as an incorrect guess 2) it can only replace one letter in the secret word if there are multiple it will give me an error & end the program. & 3) if I enter 9 to quit, it does not quit.
Thanks in advance for any help. I can add code if needed ( I am only posting the main body ATM.)
public static final int DICTIONARY = 15000;
public static final int GUESSES = 8;
public static final int SECRETLENGTH = 20;
public static void main(String[] args) {
int usedSize = 0, randomWord, guesses = GUESSES;
String word, secretWord, guess, incorrectGuess, correctWord, playAgain;
char letter;
try
{
// Set up connection to the input file
Scanner hangmanDictionary = new Scanner(new FileReader("dictionary.txt"));
String [] dictionary = new String [DICTIONARY];
while (usedSize < DICTIONARY && hangmanDictionary.hasNextLine()) {
dictionary[usedSize] = hangmanDictionary.nextLine();
usedSize++;
}
kbd.nextLine();
clearScreen();
randomWord = pickRandom(DICTIONARY);
word = dictionary[randomWord];
secretWord = secret(word);
//comment out when done testing
System.out.println(word);
System.out.println("Here is the word to guess: " + secretWord);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
do {
while (!guess.equals("9") || !(guess.equals(word) && guesses > 0)) {
letter = guess.charAt(0);
incorrectGuess = "";
incorrectGuess += letter;
if (word.indexOf(letter) < 0) {
guesses--;
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guess = kbd.next();
}
else {
//FINSH THIS
correctWord = correctWord(guess, word, secretWord, letter);
System.out.println(correctWord);
System.out.println("Incorrect guesses: " + incorrectGuess);
System.out.println("Number of guesses left: " + guesses);
System.out.println("Enter a letter to guess, or 9 to quit.");
guesses--;
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing!");
System.exit(0);
}
if (guess.equals(word)) {
System.out.println("You won!");
}
if (guesses == 0) {
System.out.println("You are out of guesses.");
}
System.out.println("Play again? Y/N");
playAgain = kbd.nextLine().toUpperCase();
} while (playAgain.equals("Y"));
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
Here's my guess:
Did you forget to put guess = kbd.next(); if the user guessed a correct character?
The inner while loop is your main problem, i.e. think about what happens when you enter a valid letter (guess), in that case the first condition of the while loop OR condition is TRUE (assuming you don't have a 9 in your secret word), so the while loop is entered without entering the second part of the OR condition. After that you enter the else part of the IF statement (since it's a valid guess) but in the else part you're not asking for the next guess, so it returns to the start of the while loop with the same guess and hence infinite loop.
Similarly, if you enter 9 to exit !guess.equals("9") evaluates to FALSE, so the second part of the OR condition is entered, in the second part
!(guess.equals(word) && guesses > 0) evaluates to TRUE (unless the secret word contains a 9) so you enter the WHILE loop which is invalid. etc ...
Try to write small parts of the code using known parameters and then bring it all together, that way it'll be easier to construct and follow the logic.

Do-While Qualifiers and Totalling in Java

I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard

Having Problems With do...while Loop

I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case

Categories

Resources