for some reason I am having an issue where the scanner keeps getting no input and doesn't wait for the user to actually input anything, leading to an infinite loop. This is what my code looks like:
Scanner kb = new Scanner(System.in); //Takes user input
System.out.println("Please enter your name");
String input = "";
if(kb.hasNextLine())
{
input = kb.nextLine();
}
while(input.isEmpty())
{
System.out.println("Please try again: ");
if(kb.hasNextLine())
input = kb.nextLine();
}
System.out.println(input);
I know issues can occur if I was using kb.next() instead of nextLine because of the buffer, but this doesn't seem to be the case. I'm pretty confused and think this should be simple enough but unfortunately it's not. All it does for me is print "Please try again:" over and over without waiting for my input. Any help would be appreciated.
Related
I'm a beginner in Java, so I apologize if this seems too easy for you to reply, still I hope I can get a little help from here.
I wanted to get an input from the user with Scanner, writing a sentence.
Then the user would pick a word from that sentence.
And then with string.indexof(""), the program should count from which number the word starts in that sentence.
But the result is always -1. And I don't understand why.
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
y=sc.next();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.next())));
But the result is always -1. And I don't understand why.
The only scenario in which -1 will be returned is if there is no such occurrence of the specified String.
Scanner#next() only returns what comes before a space, meaning anything after space is ignored. It seems that you'll need to use the Scanner#nextLine to store the whole sentence rather than Scanner#next().
e.g.
y = sc.nextLine();
{
String a,b;
Scanner sc= new Scanner(System.in);
System.out.println("Please write a sentence");
String y=sc.nextLine();
Scanner sc2 = new Scanner(System.in);
System.out.println("Please pick a word from that sentence");
System.out.println("The word starts from=" + (y.indexOf(a=sc2.nextLine())));
}
I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}
I've been having trouble using java's Scanner class. I can get it to read my input just fine, but the problem is when I want to output something. Given multiple lines of input, I want to print just ONE line when all the input has been read completely. Here's the code I use for reading input:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in); //scanner reads block of input
while(scanner.hasNextLine()){
//body of loop goes here
String s = scanner.nextLine();
Scanner ls = new Scanner(s); //scanner to parse a line of input
while(ls.hasNext()){
//body of nested loop goes here
ls.next();
}
}
System.out.println("Fin");
}
Even when all lines of input have been read, the program doesn't reach the System.out.println message. (Note that the message can't go anywhere else or it will output as many times as the loop is run). How do I fix this? Any help would be greatly appreciated.
As I can see in your outer while loop you have used
scanner.hasNextLine();
method. This method gets blocked if it has to wait for the input. Also you have
Scanner scanner = new Scanner(System.in);
statement. So the system.in will be waiting for input all the time, hence the hasNextLine() method has to wait for the input.
That is why the control gets stuck in the loop and can't proceed further.
To fix it you can first store input in a string variable and the call the scanner constructor on it.
You are reading from an Infinite stream in this case. hasNextLine() will keep returning true if there is another line in the input of this scanner. As its a System.in, it will keep reading from the Keyboard, unless you terminate it or tell the stream to stop.
Press "ctrl+Z" in the end, you will see that it works.
Edit : You could do something like this...
Scanner scanner = new Scanner(System.in); //scanner reads block of input
int BLOCK_SIZE =3,count=1;
while(scanner.hasNextLine()){
//body of loop goes here
String s = scanner.nextLine();
Scanner ls = new Scanner(s); //scanner to parse a line of input
while(ls.hasNext()){
//body of nested loop goes here
ls.next();
}
if(count++==BLOCK_SIZE)
{
break;
}
}
System.out.println("Fin");
}
You need to tell the program that there is going to be no more input. This is done by appending an EOF character. This can be done manually on Linux by pressing Ctrl-D in the console. I think on Windows you can press Ctrl-Z. The stream will be automatically closed if you are piping input from one program to another.
eg.
cat filename | java MyJavaProgram
The magic of
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
Is that there will never stop being input from System (unless you close the input with ctrl+d (for macs)).
To stop the loop, I suggest throw something more in the condition than just hasNextLine().
E.g.
Scanner scanner = new Scanner(System.in); //scanner reads block of input
int BLOCK_SIZE =3,count=1;
while(scanner.hasNextLine() && count++ <= BLOCK_SIZE){ //<- Use count here.
//body of loop goes here
String s = scanner.nextLine();
Scanner ls = new Scanner(s); //scanner to parse a line of input
while(ls.hasNext()){
//body of nested loop goes here
ls.next();
}
}
System.out.println("Fin");
}
I have been trying to figure out how to input multiple tokens at one time using the Scanner class. I found some code that works perfectly. I know that the Scanner.hasNext method can block indefinitely. Why does the line keyboard = new Scanner(keyboard.nextLine()); in this code keep it from doing this?
Scanner keyboard = new Scanner(System.in);
LinkedList<String> ll = new LinkedList<String>();
System.out.println("Please enter your full name: ");
keyboard = new Scanner(keyboard.nextLine());
while(keyboard.hasNext())
{
System.out.println("tag ");
ll.add(keyboard.next());
}
System.out.println(ll);
Thanks!
keyboard will be a Scanner which reads tokens from the first line of input.
When you use the Scanner(String str) constructor, the resulting scanner will use str as input.
If that's clear to you, you probably just need to understand that the terminal IO is line-buffered. This means that the scanner will have nothing to read until you press return.