Deal with console input (newline) [duplicate] - java

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.

Related

how can you repeat a statement if a condition is not reached in java [duplicate]

This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 2 years ago.
I'm trying to make a program that asks you to input some data as a string then if the string is more than 6 characters long it will ask you to do it again until you input an answer with less than 6 characters then moves on to the next question, how can i do this?
You can do it without a break, using a boolean variable.
boolean flag = true;
String answer;
while(flag){
System.out.println("Enter a string with less than 6 characters:");
answer = input.nextLine();
if(answer.length() > 6){
System.out.println(answer + " has more than 6 characters. Please try again!");
}else {
flag = false;
}
}
I would recommend using a while loop that is always true, then break when condition is met.
while (true) {
System.out.println("Enter answer: ");
String answer = sc.nextline();
if(!answer.length() > 6) {
// do stuf
break;
}
}

Repeating the program for the user [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am a beginner in Java, I have written a simple input java program. I am giving the user the option to repeat the program with a do while, however it's not properly functioning. Can someone point my mistake please?
public static void main(String args[]){
char repeat = 0;
Scanner input = new Scanner(System.in);
do{
String word = null;
boolean oneWord = false;
while(!oneWord){
System.out.println("Please enter a word: ");
try{
word = input.nextLine().toLowerCase();
word= word.trim();
int words = word.isEmpty() ? 0 : word.split("\\s+").length;
if(words==1 && word.length()>1 && word.length()<100){
System.out.println("Success");
oneWord = true;
System.out.println("Continue(Y/N)");
repeat = input.next().charAt(0);
}else{
System.out.println("Failure.");
}
} catch (Exception e) {
System.out.println("Exception occurred");
}
}
}while(repeat=='Y'|| repeat=='y');
input.close();
}
I would suggest you using nextLine() function of Scanner class instead of next() function.
See the difference here
Even tho its a duplicate, have a look at the line
repeat = input.next().charAt(0);
and change it to
repeat = input.nextLine().charAt(0);
This will solve your problem. For further information regarding the problem, read the duplicate link.

hasNext() of Scanner keeps looping [duplicate]

This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.

Why does this code using nextInt() loops forever? [duplicate]

This question already has answers here:
Endless while loop problem with try/catch
(2 answers)
Closed 7 years ago.
Below code,
import java.util.Scanner;
public class Dummy {
static Scanner sc = new Scanner(System.in);
public static int getIntegerInput(String prompt){
int choice = 0;
for(;;){
System.out.print(prompt);
try{
choice = sc.nextInt();
break;
}catch(java.util.InputMismatchException ex){
System.out.print("What??? ");
}
}
return choice;
}
public static void main(String[] args) {
int choice = getIntegerInput("Enter a number: ");
} //end main
}
does not stop for next user input, if the first user input raised an exception.
How do I understand this problem in the above code? placing sc.next() in catch resolves the problem. But I'm still not clear what is going on under the hood? What is the right approach to resolve this problem?
When nextXYZ() fails to consume a token it leaves it in the InputStream. Here, you are looping over the same input endlessly - each iteration, you attempt to consume this token, throw an exception if it isn't an integer, catch it, and try reading it again - forever.
EDIT:
In order to work around this, you could use next() to consume that token and move on to the next one:
for(;;) {
System.out.print(prompt);
try{
choice = sc.nextInt();
break;
} catch(java.util.InputMismatchException ex) {
sc.next(); // here
}
}
The problem with Scanner next() are they will not advances if the match is not found. And the character for which it failed remain in the stream. Hence its very important to advance the scanner if you found non intended character.
You can use next() method which actually consumes any character or you can use skip method passing skip pattern.
Use hasNext() to know whether a valid match is present or not. If not then consume that character using above said methods.
If it doesnt find an int on the next like, it throws an error. This error is then caught by your program, so the break is never hit because the error jumps over it whenever a non-int (including nothing) is found.

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

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();

Categories