This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I'm currently making a Tic Tac Toe game. when a player wins and is asked if they want to play again, I call the Playing(); method to restart the game. The issue I'm having is that it loops the Playing(); without stopping at the first Scanner.
How can I make the loop stop at the first Scanner (which asks the user to enter their [row]?
Output when A player agrees to restart :
Enter [Row] : Please enter a number :
Enter [Row] :
Playing() Method
public static void Playing() {
String line;
// Check if the user's input is a number. If not, retry!
while (true) {
try {
System.out.print("\nEnter [Row] : "); //Tell user to input Row
line = input.nextLine();
row = Integer.parseInt(line) - 1;
System.out.print("Enter [Col] : "); //Tell user to input Col
line = input.nextLine();
col = Integer.parseInt(line) - 1;
break;
} catch (NumberFormatException e) {
System.out.print("Please enter a number : ");
break;
}
}
//Check if their input for [row][col] is valid
if (row < 0 || row > 2 || col < 0 || col > 2) {
System.out.print("Oops! Invalid input. Try again");
Playing();
} else if (Board[row][col] != '_') {
System.out.print("This position is already taken. Try again");
Playing();
} else {
Board[row][col] = player;
moveCount++;
DisplayBoard();
GameOver(); //Check if anyone won. If not, continue the game
}
}
Replay() Method
public static void Replay() {
/*
* Check if the user wants to play again
*/
System.out.print("Would you like to play again?(Y or N) : ");
while (true) {
String retry = input.next();
if ("y".equalsIgnoreCase(retry)) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
Board[r][c] = '_';
}
}
System.out.print("-----------------------------------------------------\n");
DisplayBoard();
Playing();
break;
} else if ("n".equalsIgnoreCase(retry)) {
System.out.println("Thank you for Playing!");
System.exit(1);
// If the user enters an invalid input, this will ask them to try again
} else {
System.out.print("Invalid input. Would you like to play again?(Y or N) : ");
}
}
}
First of all, what is the reason for using
line = input.nextLine();
row = Integer.parseInt(line) - 1;
where one can actually get the integers using nextInt() method available from Scanner
line = input.nextInt();
row = line - 1;
And to answer your question, I think this is the culprit which causes to skip your inputs
String retry = input.next();
In this line if your enter some keyword, say "Hello" and hit enter which is "Hello\n" the next method only takes "Hello" and the \n will skip your nextLine() method. So I suggest you to try adding another nextLine() after this line
String retry = input.next();
input.nextLine();
Note: This is only a guess for a problem, I haven't actually debugged your code by running on my end-system.
Related
I have minor problem with part of the algorithm in this code. Here is a description of the task:
User types in a choice between the numbers 0,1,5 or 2.
0 ends the program,
1 prompts the user to add a name and email to the 2d array,
5 prints out all of the names and email pairs the user typed in. And
2 allows the user to search for an exact match by typing in the name and in return the program prints out the email of the name the user is looking for.
Problem is with the choice == 2 algorithm. It seems that there is a problem and it does not work properly. No matter what the user types it will always print out "Match is found!" and return the wrong email.
Any suggestions?
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[][] rolodex = new String[257][2];
System.out.println("Welcome!");
int choice;
int p = 0;
String matchValue;
boolean isFound = false;
do {
System.out.println("Please select an option: ");
choice = in.nextInt();
in.nextLine();
if (choice == 1 && p < rolodex.length) {
System.out.println("What's the name?");
rolodex[p][0] = in.nextLine();
System.out.println("What's the email?");
rolodex[p][1] = in.nextLine();
p++;
} else if (choice == 5) {
for (int i = 0; i < p; i++) {
System.out.println("email: " + rolodex[i][1]);
System.out.println("name: " + rolodex[i][0]);
System.out.println("--------------------");
}
} else if (choice == 2) {
System.out.println("Type in the name of the email you want: ");
matchValue = in.nextLine();
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0]) && !isFound) {
isFound = true;
}
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
} else {
System.out.println("Match not found!");
}
}
}
} while (choice != 0);
System.out.println("Thank you! Have a nice day!");
}
}
The initializing of the boolean variable and not re-initializing in the following repetitions was causing the problem in your code. Hence, in the block of code I am suggesting below, I have removed the boolean variable altogether. Furthermore, you could try by breaking off from the loop once the correct email match has been identified by the program.
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0])) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
break;
} else if (i == (p - 1)) {
System.out.println("Match not found!");
}
}
You need to reset the value of isFound after it has been set to true. You have not done so, hence the wrong output.
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
//Add this to your code
isFound = false;
}
There is another problem with your search. You have to stop the loop once the match has been found. You have not done so.
I do suggest you try to do it on your own. You should also check #Ayyan Tahzib answer as it contains a hint on correcting this problem of your searching procedure.
If you face any problems, do comment. I will be happy to help you.
I am new to programming and got stuck on a task. It says that user should input their name and the size of it and then it would be printed in stars with that size, also it should use loops in this program not just sout stars.
I have no idea on how to approach this problem so I would really appreciate it if anyone could give me an idea :)
What I have tried so far is:
(update):
i was able to do my whole coding and reach the thing i want, but what i'am stuck in a point, where if user update the size which is n , how i can use it in my whole switch while printing where Pattern(A) prints star version of letter
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int option = 0;
while (option != 3) {
System.out.println("Hello, Welcome to Işık NameIt program. ");
System.out.println("----------------------------------------------------------------");
System.out.println("The following options are available for you:\n" +
"1) Display a name\n" +
"2) Change the size\n" +
"3) Exit Program");
System.out.print("Choose an option: ");
option = input.nextInt();
int n = 5;
switch (option) {
case 1:
System.out.print("What is your name?! ");
String name = input.next();
for(int i=0; i<=name.length()-1; i++) {
char letter = name.charAt(i);
switch (letter){
case 'a':
PatternA(n);
break;
case 'y':
PatternY(n);
break;
case 'h':
PatternH(n)
break;
case 'm':
PatternM(n)
break;
}
}
break;
case 2:
System.out.print("What is the new size? ");
int nupdate = input.nextInt();
}
}
}
public static void PatternA(int n) {
// Outer for loop for number of lines
for (int i = 0; i < n; i++) {
// Inner for loop for logic execution
for (int j = 0; j <= n / 2; j++) {
// prints two column lines
if ((j == 0 || j == n / 2) && i != 0 ||
// print first line of alphabet
i == 0 && j != 0 && j != n / 2 ||
// prints middle line
i == n / 2)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
System.out.println("-----------------------------------------------------------------------");
}
I'm not 100% clear on what you are expecting as your output, if you provided a sample of that it would be helpful. However, with the way you have your program implemented right now you will want to throw your switch statement inside of a while loop to continue executing the program until a 3 is input by the user.
while (option != 3)
{
switch (option)
{
// code
}
// code
option = input.nextInt();
}
Within that while block you can execute whatever statements you want when the user inputs their specified option. Depending on the requirements of the code you should also consider validating the user input. What happens if they don't put in a 1, 2, or 3?
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Hello, Welcome to Işık NameIt program. ");
System.out.println("----------------------------------------");
System.out.println("The following options are available for you:\n" +
"1) Display a name\n" +
"2) Change the size\n" +
"3) Exit Program");
System.out.print("Choose an option: ");
int option = input.nextInt();
int size = option.length;
while(option !=3){
switch (option){
case 1:
for(int index = 0; index <= size; index++) {
System.out.print("*");
}
System.out.println(" ");
case 2:
System.out.print("What is the new size? ");
size = input.nextInt();
input.nextLine();
case 3:
break;
}
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
if (sum < 6) {
System.out.println("You win");
System.out.println();
// Does the user want to retry?
System.out.print("Would you like to retry?(Y or N) : ");
String retry = input.nextLine();
while (true) {
// If they say y or Y, roll again
if (("y".equals(retry)) || ("Y".equals(retry))) {
roll();
// Check for anything other than y and Y
} else if (("n".equals(retry)) || ("N".equals(retry))) {
System.out.println("Closing");
break;
} else if (!("y".equals(retry)) || !("Y".equals(retry))) {
System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
retry = input.nextLine();
System.out.println();
}
}
} else if (sum > 6) {
System.out.println("You lose");
System.out.println();
System.out.print("Would you like to retry?(Y or N) : ");
String retry = input.nextLine();
while (true) {
if (("y".equals(retry)) || ("Y".equals(retry))) {
roll();
} else if (("n".equals(retry)) || ("N".equals(retry))) {
System.out.println("Closing");
break;
} else if (!("y".equals(retry)) || !("Y".equals(retry))) {
System.out.print("Invalid input. Would you like to retry?(Y or N) : ");
retry = input.nextLine();
System.out.println();
}
}
}
I'm trying to make a dice game where the game will keep rolling the dices when the user inputs "y" or "Y". I also want it to stop the game and say "Closing" when the user inputs "n" or "N".
The issue is, when the user inputs "n" or "N", it will print out "Closing" but the loop doesn't stop and the game will roll the dices again. How to I make my while() loop stop when the user inputs "n" or "N"?
Here's the output when the user chooses to stop the game ("n" or "N") : Would
you like to retry?(Y or N) : n
Closing
Rolling...
You rolled : 1 & 4
Sum = 5
You win
I'm sorry for such basic question, I am new to programming.
Move the line String retry = input.nextLine(); into the while loop (in both if branches). Currently you read in one input and then compare that non-changing input over and over again.
I wondering is it possible to skip past a do while loop or even exit a method halfway through it if certain conditions are met?
Heres an example of what I mean ( everything works in this )
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
boolean bookExists = false;
boolean memberIDExists = false;
boolean memberCurrentlyLoaningBook = false;
int memberID = 0;
System.out.println("You must be a member of the library to loan out a book");
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
memberID = input.nextInt();
for (int i = 0; i < members.size(); i++) {
if (memberID == members.get(i).getMemberID()) {
memberIDExists=true;
if(members.get(i).isCurrentlyLoaningBook()==false){
successful = true;
memberCurrentlyLoaningBook=true;
}
}
}
if(!memberCurrentlyLoaningBook){
System.out.println("This member is currently loaning a book");
}
if (!memberIDExists) {
System.out.println("This member ID does not exist");
}
} while (successful == false);
EDIT
do while loops that are in the same method
do { these other do while loops are after this first one and do other things
} while (); ( I haven't included what they do as it takes up too
do { much space)
} while();
I have an option here to exit to the main menu, but i also have a do while loop after this, so whenever I enter 9 it just exits the current to while loop and goes on to the next one, is there anyway that I can skip past all the proceeding do while loops after I press 9, or even exit the method?
In your case continueor breakcould be useful. But if you want to exit the method you could just do it with return.
Try this, I have added break; when user enter "9" as an input. It will then come out of the do while loop.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
break;
}
EDIT:
Yes to Check for the next loop, add a condition with that loop
loop(your original condition && !successful)
{
}
EDIT 2:
TO come out of the loop and avoid other do while loops in the method, you can just return;
It will take back the control of the program through which this method was called.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
return;
}
I can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}