I started working on this little dice game but I need some help figuring out how to make the try again section loop after each failed attempt.
Currently the game restarts and asks the player to re-enter their name.
What I would like is for the user to just re-enter their guess
each time until they become successful.
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main (String[] args) throws IOException {
boolean run = true;
while (run) {
String[] input = new String[]{"1", "2", "3", "4", "5", "6"};
String[] sorry = new String[]{"If at first you don't succeed...", "Your luck will improve...", "Don't give up...", "Not this time..."};
Random dice = new Random();
int select = dice.nextInt(input.length);
Scanner scan = new Scanner(System.in);
System.out.println( "Hi there, may I please have your name?");
String name = scan.nextLine();
System.out.println("What a nice name...");
System.out.println("ok "+name+", please choose a number between 1 and 6");
String play = scan.nextLine();
System.out.println(input[select]);
if (!input[select].equals(play)) {
System.out.println(sorry[select]+" try again");
if (input[select].equals(play))
System.out.println("Bingo!!! "+name+" you've won 1 million imaginary dollars!");
System.out.println("would you like to play again \"Y\" or \"N\"");
String yes = "y";
String no = "n";
String answer = scan.nextLine();
if (answer.equals(yes)) {
continue;
}
if (answer.equals(no)) {
System.out.println("Thank you for playing "+name+". Good bye!");
break;
}
}
}
}
}
Put the print statement that asks name outside the while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Hi there, may I please have your name?");
String name = scan.nextLine();
while(run){
// your code
}
You can use a while loop! At the try again section, change the if to a while loop.
static String play; // Define it (not assign) outside of method
while (!input[select].equals(play)) {
System.out.println(sorry[select]+" try again");
System.out.println("ok "+name+", please choose a number between 1 and 6");
play = scan.nextLine();
}
Definition of while loop from W3Schools:
The while loop loops through a block of code as long as a specified condition is true
Related
So, I want to receive input from the user, check if they used alphabetical values and then check if it is too long. If too long, I want to start again from the top (checking if alphabetical) by calling the method I am in. However, when I start over and I type, say "Danny", this will show:
Output: "Thank you, got Danny"
Output: (length of previous, too long input) + "is too many characters, try to keep it under 30."
So somehow, it keeps the original input (that was alphabetical, but above 30) saved and it doesn't alter it when it starts over. Anyone know what I should do instead?
public static String inputPattern() {
Scanner scanner = new Scanner(System.in);
String player;
int strLength;
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
while (strLength > 30) { // Checks if not too long
System.out.println(strLength + " is too many characters, please try to keep it under 30");
inputPattern(); // Starts over again if too long
}
return player;
}
I have taken your method and modified it a bit.
It is non recursive solution.
Also in your code scanner resource was not closed at the end.
Iterative Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
inputPatternIterative();
}
public static String inputPatternIterative() {
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength = Integer.MAX_VALUE;
while (strLength > 30) { // Checks if not too long
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
if (strLength > 30)
System.out.println(strLength + " is too many characters, please try to keep it under 30");
}
scanner.close(); // Closing scanner resource after use.
return player;
}
}
Output :
Please enter your name:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Thank you! Got aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
70 is too many characters, please try to keep it under 30
Please enter your name:
aaaaaaaaaaaaaaaaaaaa12
Please stick to the alphabet!
coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
Thank you! Got coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
75 is too many characters, please try to keep it under 30
Please enter your name:
Danny
Thank you! Got Danny
EDIT : with the suggestion made by #Dev-vruper here is updated easy recursive code
Recursive Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
inputPatternRecursive(sc);
sc.close();
}
public static String inputPatternRecursive(Scanner sc) {
System.out.println("Please enter your name:");
String player = sc.nextLine();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
inputPatternRecursive(sc);
} else {
System.out.println("Thank you! Got " + player);
if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30");
inputPatternRecursive(sc);
}
}
return player;
}
}
This should solve your problem in a pretty easy way:
public static String inputPattern(){
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength;
boolean bShowedInstruction = true;
System.out.println("Please enter your name:");
while (true) {
if (!bShowedInstruction)
System.out.println("Please enter your name:");
bShowedInstruction = false;
player = scanner.next();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
}
else if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30!");
}
else
break;
}
System.out.println("Thank you! Got " + player);
return player;
}
There's no need for a recursion. A simple while(true) loop does the trick.
It's a pretty clean solution keeping unnecessary scan-methods out of the game.
I am making one of my first java projects checking if a user input word (no numbers or symbols) is a palindrome. I used the method outlined here: https://stackoverflow.com/a/4139065/10421526 for the logic. The code works per-request but I am having trouble re-prompting the user after invalid input as it seems to "block" the ability of my code to accept valid input, printing my "retry" message. I have also tried the do while version but I ended up with formatting errors. I think the way I define my stringOut variable is giving me trouble but Im not sure how to change that without making a duplicate as eclipse says. Here is the closest I could get after dozens of tries going in circles:
import java.util.Scanner;
public class PalindromTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Input word to test: ");
String stringIn = in.nextLine();
String stringOut = new StringBuilder(stringIn).reverse().toString();
while (!stringIn.matches("[a-zA-Z]+")) {
System.out.println("Invalid input, try again.");
in.next(); //stops infinite error loop
}
if ((stringIn.equalsIgnoreCase(stringOut))) {
System.out.println("Palindrome detected");
System.out.println("You entered: " + stringIn);
System.out.println("Your string reversed is: " + stringOut);
} else {
System.out.println("Not a palindrome");
}
}
}
change in.next(); in while loop to stringIn= in.next(); and after while loop add stringOut = new StringBuilder(stringIn).reverse().toString(); .
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Input word to test: ");
String stringIn = in.nextLine();
String stringOut = new StringBuilder(stringIn).reverse().toString();
while (!stringIn.matches("[a-zA-Z]+")) {
System.out.println("Invalid input, try again.");
stringIn= in.next(); //stops infinite error loop
}
stringOut = new StringBuilder(stringIn).reverse().toString();
if ((stringIn.equalsIgnoreCase(stringOut))) {
System.out.println("Palindrome detected");
System.out.println("You entered: " + stringIn);
System.out.println("Your string reversed is: " + stringOut);
} else {
System.out.println("Not a palindrome");
}
}
}
A very good use-case to use do-while loop. You use this loop when you have to make sure that your statements are executed at least once. And the subsequent execution is executed only if it matches a condition. In this case, that condition would be validating your input.
Scanner in = new Scanner(System.in);
String prompt = "Input word to test: ";
String stringIn;
do {
System.out.println(prompt);
stringIn = in.nextLine();
prompt = "Invalid input, try again.";
}
while (stringIn.matches("[a-zA-Z]+"));
If the input is non-numeric the while condition would be true and will make this loop run again, hence asking for new input. if the input is numeric the while condition will be false hence exit the while loop and will give you user input in stringIn variable.
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
String answer;
//answer = input.nextLine();
do
{
//input.hasNextLine();
System.out.println("MAIN MENU");
System.out.println("- Start a new Game (S)");
System.out.println("- Exit (E)");
System.out.println("Please enter your choice: ");
answer = input.next();
if (answer.equals("s") || answer.equals("S"))
{
Hangman h1 = new Hangman();
h1.getWord();
h1.printData();
h1.CountTheLetters();
h1.GiveTheLetters();
}
input.hasNext();
} while (answer.equals("e") || answer.equals("E"));
System.out.println("Thank you for the game");
}
}
why this loop runs only one time and it dont ask again for new entrance? the menu in first time is appearing i enter s and i play the game. then i want to ask me again but it doesnt do it. why?
......
Because answer doesn't equal "e" nor "E". Additionally, you need to check that the scanner still has elements to read.
Change the line to:
} while (input.hasNext() && !answer.equals("e") && !answer.equals("E"));
This question already has answers here:
Breaks from loop
(3 answers)
Closed 8 years ago.
I have looped my code so it keeps repeating until a "yes" or a "no" is given when being asked "Continue?". But my code breaks from the loop after entering a random value and then yes.
for example:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
It should say:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
Add or delete another name?
actual code
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
Scanner myScan = new Scanner(System.in);
Scanner scanRedo = new Scanner(System.in);
String userRedo;
String userResponse;
while (scan.hasNext())
names.add(scan.next());
do {
System.out.print("Add or delete another name? ");
userResponse = myScan.next();
if (userResponse.equalsIgnoreCase("add")) {
System.out.print("Please enter a name you want to add: ");
names.add(myScan.next());
} else if (userResponse.equalsIgnoreCase("delete")) {
System.out.print("Please enter a name you want to delete: ");
names.remove(myScan.next());
} else {
System.out.print("Invalid Choice");
}
PrintWriter writer = new PrintWriter("namesupdated.txt");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
System.out.print("Continue? ");
userRedo = scanRedo.next();
} while (userRedo.equalsIgnoreCase("yes"));
do { // THIS LOOP IS HERE BECAUSE IF THE USER ENTERS A VALUE OTHER THAN CONTINUE, YES OR NO, THE QUESTION REPEATS
if(userRedo.equalsIgnoreCase("no")) {
System.out.print("Thank You.");
userRedo = scanRedo.next();
} else if (!userRedo.equalsIgnoreCase("yes")) {
System.out.print("Continue? "); // LOOP ENDS EARLY HERE
userRedo = scanRedo.next();
}
} while (!userRedo.equalsIgnoreCase("yes")); // NOT SURE HOW TO RESTART PREVIOUS LOOP
scan.close();
myScan.close();
scanRedo.close();
}
}
The way you do this is always with a while loop with some sort of changable condition:
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
...
System.out.println("Continue? Yes or No");
String s = Scan.nextLine();
if(s.equals("No")) {
stop = true;
}
}
I need help with looping my code in Java. So far I have:
import java.util.Scanner;
public class chara{
public static void main(String[]args){
int count = 0;
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
return;
}
else
{
}
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
return;
}
else
{
}
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
}
}
The code does everything I want it to except that when the string condition is not met (user<7, letter!=1) the program terminates and what I need it to do is ask the question again. Does anyone know how I can achieve this?
You need to put your looping code in method that can be called, then when the conidtion is not met you can go back to your question, and depending on that condidtion, quit the program, or call the loop method.
You just need a loop with a break condition, this should do it for you:
Scanner input = new Scanner(System.in);
System.out.println("Input a string");
String user=input.nextLine();
while (true)
{
if(user.length() <7 ) {break;}
input = new Scanner(System.in);
System.out.println("Too long, input a string < 7");
user=input.nextLine();
}
if(user.length()<7)......
A simple way would be to wrap your main logic within a loop with a boolean condition. This condition stays true when there is an "error" in the input. The condition is then false when the user proceeds as wanted.
Your code would look as so :
import java.util.Scanner;
public class Tester{
public static void main(String[]args){
int count = 0;
boolean keepGoing = true;
Scanner input = new Scanner(System.in);
while(keepGoing) {
System.out.println("Input a string");
String user=input.nextLine();
if(user.length()<7)
{
keepGoing = true;
//enter an error message here
}
else
{
System.out.println("Now input a letter to be replaced");
String letter = input.next();
if(letter.length()!=1)
{
keepGoing = true;
//enter an error message here
}
else
{
String user2 = user.replace(letter, "-");
String user3 = user.replace(letter, "");
count += (user.length() - user3.length());
System.out.println(user2);
System.out.println(user3);
System.out.println("#"+letter+"'s: "+count);
keepGoing = false;
}
}
}
input.close(); //Close resources
}
}
Unrelated
The convention is that class names start with a capital letter. In your case your class should be Chara, not chara.
Also, when opening resources make sure you close them. This is to avoid having resources leaked. Some IDEs will tell you something like this Resource leak: 'input' is never closed. It's a good idea to use a good IDE to help you with potential problems like this one.