Why is my java program skipping user string input? [duplicate] - java

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 7 years ago.
static boolean check(double money)
{
String scont, yes = "yes", no = "no";
boolean bcont;
if (money == 0) {
System.out.println("You are broke and can no longer play.");
bcont = false;
return bcont;
}
System.out.println("You have " + form.format(money) + " left.");
System.out.println("Would you like to continue playing? (Yes or no?)");
scont = in.nextLine();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
}
else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
}
else {
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
}
}
This is, obviously, only a singular function in my program. When it gets to scont = in.nextLine(); it skips the user input and breaks the loop the function is in, in the main function.

More than likely you're reading the money value from the Scanner which is not consuming the newline characters. In that case add in.nextLine() to consume this character
double money = in.nextDouble();
in.nextLine(); // add
boolean result = check(money);
(Of course BigDecimal is the preferred datatype for monetary amounts)

A few observations:
You should always use .equals() in place of == for String
comparison in Java
But, this is a moot point because equalsIgnoreCase() returns a boolean value anyway; you don't need to perform boolean evaluations in your conditionals
I suspect you may be incorrectly making use of the Scanner class, as observed by #David Wallace
It might pay to check your usage of the Scanner class. You can identify whether or not this is the root of your problem by simply using a BufferedReader to temporarily receive the user input.
e.g.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
...
scont = br.readLine();

Related

How do I use boolean method correctly if I need two options?

The question is, if I need to chose only from two options in boolean method (Yes or No) how do I put it in IFs?
I try to do like this (see below), it underlines very last brace. If I use default return outside while (but I don't want to), it underlines first return (after first if).
static boolean isAnotherGamer() {
System.out.println("Play another game? Type in Y or N");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
while (true) {
if (answer.equalsIgnoreCase("Y")) {
break;
return true;
} else if (answer.equalsIgnoreCase("N")) {
break;
return false;
}
System.out.println("Input mismatch");
} //IDE underline this brace
}
Here is how I would do it. This allows any part of yes or no to be entered. I think it best to pass a Scanner instance rather than creating one each time. Using a regular expression allows for some latitude in the answer.
^$ - beginning and end of string.
(?i) - ignore case
ye?s? - says must have y but e and s are optional.
static boolean isAnotherGamer(Scanner scanner) {
System.out.println("Play another game? Type in Y(es) or N(o)");
while (true) {
String input = scanner.nextLine();
if (input.matches("(?i)^ye?s?$")) {
return true;
}
if (input.matches("(?i)^no?$")) {
return false;
}
System.out.println("Incorrect response, please enter Y(es) or N(o)");
}
}
Why can you not validate the input first, and then after the input is either a yes or no, decide on what to do. If it is not either, you can make the repetition statement continue to run until after you get what you need. The location of your return statement is the problem because if either if or else if statements are not true, the method will not return a boolean as your method signature suggests, and your method will just be an infinite loop.
Your method is declared to return a boolean. There is no return statement in the flow.
Assume you go into the endless loop. At this moment we evaluate what the user entered (why do we do that inside the endless loop? The answer does not change inbetween, does it?)
If it is 'y', we break the loop.
If it is 'n', we break the loop.
In any other case we print something and remain in the loop.
But as soon as the loop was broken -> where is the return statement?
So from my POV, the function should look like this:
static boolean isAnotherGamer() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Play another game? Type in Y or N");
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase("Y")) {
return true;
} else if (answer.equalsIgnoreCase("N")) {
return false;
}
System.out.println("Input mismatch");
}
}
Because you've not set a default return value, if the user doesn't choose either "Y" or "N" then nothing is going to be returned so that's why you're getting an error.
Additionally, you shouldn't be putting any code after your break statements as those lines will be completely ignored (again, nothing returned as your return statements are after your breaks.)
You can just completely remove those break statements if you're just wanting to quit that method once you've got your boolean value or you can update a boolean variable for future use if you're wanting to keep running code inside your method. (I've provided an example of this)
System.out.println("Play another game? Type in Y or N");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
//To store the state of the user's answer
boolean providedAnswer = false;
//if the answer was yes, set the boolean's val to true
if(answer.equalsIgnoreCase("Yes")){
providedAnswer = true;
}
//output the boolean's value
System.out.println("User wanted to play again? " + providedAnswer);
//return the boolean value
return providedAnswer;
}```

How can I use something like (input == '\n') to determine when to stop accepting user input?

I have to convert an infix operation to a postfix one, however the infix operation must be inputted as one character per line. So instead of inputting something like this: 3-2, you would need to input something like this:
3
-
2
I had an idea of using =='\n' to determine whether the inputted character is a next line function so that would determine the end of the equation, but it doesn't work. I tried replacing it with a different character such as =='e', and that works perfectly. What can I do to fix this?
String string = "";
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag==true)
{
char charIn = input.next().charAt(0);
string = string + charIn;
if (charIn=='e') //inputting 'e' gives me my desired result
{
flag = false;
}
}
//code that passes string to InfixToPostfix method and prints out the answer. this part works fine
You did not specify that this was a school assignment or that you had certain restrictions, so this answer is admittedly a shot in the dark.
I would recommend using a StringBuilder within a loop and reading nextLine() instead of simply next(). This allows you to determine if the entry was empty (ie: the enter key was pressed without entering a character).
Also, we should allow the user to enter more than one character anyway (what happens when they try to enter 22 as a number). Abandoning the char type allows for this.
public static void main(String[] args) {
StringBuilder string = new StringBuilder();
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag) {
// Capture all characters entered, including numbers with multiple digits
String in = input.nextLine();
// If no characters were entered, then the [ENTER] key was pressed
if (in.isEmpty()) {
// User is done adding characters; exit the loop
flag = false;
} else {
// Otherwise, get the text entered and add it to our final string
string.append(in);
}
}
System.out.println("Final String: " + string);
}
Does this meet your needs?
This should do what you want. Reading just the first character has its limitations.
String string = "";
Scanner input = new Scanner(System.in);
boolean flag = true;
while (flag==true)
{
String nextLine = input.nextLine();
char charIn;
if(nextLine.length() > 0) {
charIn = nextLine.charAt(0); //This is bad idea as you can only operate on single digit numbers
System.out.println("charIn = " + charIn);;
string = string + charIn;
}
else
flag = false;
}

While loop breaks after bufferedInput change [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm doing some basic homework, and it's honestly all stuff I know. But I decided to jazz it up a little, and something I'm missing is causing an unexpected error.
The idea is to use a while loop which asks if the user would like to do something. So long as they say yes, the loop continues the operations that it holds (in this case rounding a decimal to an int). However, as soon as I enter yes, or anything really, the loop breaks there and won't continue on to the rounding portion.
public class DecimalRounder {
//Main class method that starts and ends the program. It is prepared to throw an IO exception if need be.
public static void main(String args[])throws IOException
{
//Main initializes a new reader to take input from System.in
InputStreamReader rawInput = new InputStreamReader(System.in);
//Main then initializes a new buffer to buffer the input from System.in
BufferedReader bufferedInput = new BufferedReader(rawInput);
//Main initializes other used variable
double castInput = 0.0;
String contin = "yes";
//Program then sets up loop to allow user to round numbers till content
while (contin == "yes")
{
//Program asks user if they'd like to round.
System.out.println("Would you like to round? Type yes to continue... ");
contin = bufferedInput.readLine();
//If user says yes, rounding begins. ERROR FOUND HERE?
if (contin == "yes") //INPUT "yes" DOESN'T MATCH?
{
//Program then requests a decimal number
System.out.println("Please enter a decimal number for rounding: ");
String givenLine = bufferedInput.readLine();
//rawInput is worked on using a try catch statement
try {
//givenLine is first parsed from String into double.
castInput = Double.parseDouble(givenLine);
//castInput is then rounded and outputted to the console
System.out.println("Rounded number is... " + Math.round(castInput));
//Branch then ends restarting loop.
}catch(Exception e){
//If the data entered cannot be cast into a double, an error is given
System.err.println("That is not a roundable number: " + e.getMessage());
//And branch ends restarting loop.
}
}
}
System.out.println("Have a nice day!");
}
}
Use .equals instead of == to compare strings in JAVA.
Try this :
contin.equals("yes")

Deal with console input (newline) [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
For a console menu in Java, I sometimes want to read integers and some strings. I have these two functions:
To get a String:
public String enterString(String question) {
System.out.println(question);
return scanner.nextLine();
}
To get an int (for a switch statement later):
public int choose(int b, String question) {
Boolean chosen = false;
while(!chosen) {
chosen = true;
System.out.println(question);
int choice = scanner.nextInt();
if(choice >= 0 && choice <= b) {
return choice;
}
else {
chosen = false;
System.out.println("Not a valid choice.");
}
}
return 0; //the compiler complains otherwise
}
However, if I use enterString() first and then choose() and then enterString(), it seems to use the newline from choose. Entering scanner.nextLine() at various places (start and end of each function) always caused problems.
How can I make any combination of the two work?
nextInt() is not going to consume the EOL. So, either scan for Int as
int choice = Integer.parseInt(scanner.nextLine());
or, consume the extra new line
int choice = scanner.nextInt();
scanner.nextLine(); // Skip
scanner.nextInt() does not consume the line-end.
You could wrap the nextLine in a while loop and ask for input again if the line is empty.

Comparing a Scanner to a String

I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.

Categories