I am trying to get some integer inputs from user by using scanner.hasNextInt() method. It works just fine but I need to type a letter to let the program know that I'm done entering integers while I want the console to know that after I press the enter key after a single line.
For example, I type
(1
2
3
y
enter)
and the program works just fine but if I type
(1
2
3
enter
enter)
nothing happens, even if I keep pressing the enter key. This is the related part of my code, if you need to take a look at it.
public class Main {
static LinkedList linkedList =new LinkedList();
public static void main(String [] args){
System.out.println("enter integer numbers");
Scanner scanner=new Scanner(System.in);
while (scanner.hasNextInt()){
linkedList.append(scanner.nextInt());
}
print();
}
}
Three steps to understand it.
Scanner uses a delimiter to break the input into tokens, the default delimiter is \p{javaWhitespace}+. Try
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.delimiter());
\p{javaWhitespace} is equivalent to java.lang.Character.isWhitespace(), so \p{javaWhitespace}+ will matches multiple characters which isWhitespace.
A line break produced by key enter is a white space. When you enter multiple enters, they will be recognized as a delimiter, not a token.
You can use s single white space, so it will take the second enter as token:
scanner.useDelimiter("\\p{javaWhitespace}");
Related
I had a simple question. I've been exploring basic input validation in java (Only accept integers or doubles etc.. from user). The code below Works great for simple applications but it did spark my curiosity; whenever you input a letter then follow it with a space then another letter, it displays the "Try again. Input numbers only " message twice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Number, BOi");
//Basic input validation. Only Accepts Integers.
while (!sc.hasNextInt()){
sc.next();//This Clears the Scanner for next input
System.out.println("Try again. Input numbers only.");
}
int userInput = sc.nextInt();
System.out.println("CONGRATS! YOU'VE ENTERED THE NUMBER: " +
userInput);
}
}
If I were to input
p p p
then the result would be
Try again. Input numbers only.
Try again. Input numbers only.
Try again. Input numbers only.
I would expect the result to just be Try again. Input numbers only. displayed once. Can anybody explain why this happens? I've heard the term "regex" thrown around but don't know if it's relevant. Thank you!
Its because next() does not consume the whole line. It only consumes the first word until space and the remaining words stays.
Thus when your loop will repeat as many words you have until it finds an int.
For example here you are giving P P P means 3 words hence thrice iteration
Thus you should use:
sc.nextLine() if you are expecting non integer and parse it
sc.nextInt(); and handle exception if someone inputs anything other
than int
Your problem is just a lack of knowledge of how Scanner really works.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So when you enter p p p, Scanner.nextInt() will split p p p into p then p and then p. Thats why you get 3 times the same message.
Use nextLine() method to get the whole line and not "skip" any whitespace.
Scanner console=new Scanner(System.in);
System.out.print("how many:");
int n=console.nextInt();
console.nextLine();
String firstName[]=new String[n];
String lastName[]=new String[n];
int zipCode[]=new int[n];
console.useDelimiter("[\t]");
for(int i=0;i<n;i++) {
System.out.print("Enter the first Name"+"Last Name"+"zipcode:");
firstName[i]=console.next();
lastName[i]=console.next();
zipCode[i]=console.nextInt();
console.nextLine();
}
Input with Tabs: Test Tst 121
firstName[i] is initialized to Test. lastName[i] is initialized to Tst. But the zipCode[i] is not initialized to 121. It is still prompting for input, but it's not taking anything I enter.
The next...() methods of a Scanner allways first scan the next token, and then aim to convert it to the correct type (for instance int in the case of nextInt()).
Now a token is a sequence of characters that is not a delimiter. Since the only delimiter you've set is a tab (\t), it will keep searching for a tab, even if you enter a new line, the search doesn't stop.
Basically there exists two solutions:
Allowing to use a new line as well:
console.useDelimiter("[\t\r\n]");
(and remove .nextLine() at the end of the loop). A consequence is that if you separate the first and the last name by a new line, the Scanner will not error on this, thus:
Test
Tst
121
will be parsed as Test Tst 121 as well, although I don't see much problems with this.
If you really want to disable this, you can set and reset the delimiter in the loop. Thus something like:
for(int i=0;i<n;i++) {
System.out.print("Enter the first Name"+"Last Name"+"zipcode:");
console.useDelimiter("[\t]");
firstName[i]=console.next();
lastName[i]=console.next();
console.useDelimiter("[\n]");
zipCode[i]=console.nextInt();
}
(but I don't see the added value in this cases).
I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?
public class TestCode{
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
String input = "";
while(!input.equals("X")){
System.out.println("Prompt user for input");
input = scan.next().toUpperCase();
calculatePolynomial(input);
}
}
public static void calculatePolynomial(String input){
//Clean up entry removing spaces and extracting polynomial names
String calculation = input.replaceAll("\\s", "");
System.out.println(calculation);
}
}
The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.
But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.
I just want the user's input to be without spaces and without a nightmare of logical errors.
When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.
To get the entire input in the user's input line, try using the nextLine() method instead.
Total Java newbie here. Working on one of my very first Java programs. Please help.
Here's what I am trying to achieve:
I need to accept user keyboard input of whitespace separated integers, copy them into an array and process them. KNOWN: user will enter only ONE line of data. I don't know how many numbers, but once they hit Enter, there won't be any more. As user input may contain words and special characters, I need to handle them with neat errors and prompt user to try again. When I run what I wrote below, I get in some kind of infinite loop where Scanner keeps waiting for additional input. How do I tell it it's over and there won't be any more input?
Here's the code:
<!-- language-all: java -->
public static void EnterInts () {
System.out.println("Enter series of integers separated by whitespace. Press Enter key when finished.");
Scanner input = new Scanner(System.in);
while (input.hasNext()){
if (input.hasNextInt(){
int i = input.nextInt();
System.out.println(i);
}
else {
System.out.println("Only integers can be entered. Try again.");
}
}
}
Seems like you should read the single line of input first, then create the Scanner to scan through that single line.
Try using a BufferedReader and InputStreamReader to read the line first:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = in.readLine();
And then create the Scanner, perhaps passing a StringBufferInputStream created from the read string into its constructor.
I was given the following code and asked to write the Solution class extending from TestList. I wrote a constructor for it (which just called super) and the printSecond2() method invoked in the last line of the code below. All other methods are inherited. Here's the code:
public class Test3A {
public static void main(String[] args) {
TestList tl = new Solution();
tl.loadList();
((Solution) (tl)).printSecond2();//prints every second element
}
}
However, the damn thing was never printing anything out, so I went into the TestList class (which was provided) and put println statements after every single line of the loadList () method:
public void loadList ()
{
if (input.hasNextInt ())//input is a Scanner object
{
int number = input.nextInt ();
loadList ();
add (number);
}
}
I discovered that I can continue to add whitespace, newlines and integers indefinitely, and that the add(number) method is only finally called when I input a character. So if I don't do that, it just sort of hangs around waiting for more input instead of moving on.
I'm confused by this as the provided sample input/output is:
sample input
1 2 3 4 5
sample output
2 4
So there's no character being inputted by the automatic marker.
I have tried overriding the method in Solution (we can't touch the other classes) and:
) changing if to while
) adding an else block
) adding an else if (!input.hasNextInt ())
None of these changed anything. I have no idea how the program is supposed to move on and get as far as calling printSecond2().
Any thoughts? I'd really like to pass my next prac test :D
When user is supposed to enter a sequence of numbers either the number of items should be provided or the input should be terminated in some manner. 1 2 3 and 1 2 3 4 are both valid inputs so scanner can't decide where to end on its own.
It can be assumed that the number sequence is terminated by EOF character Ctrl-Z on windows and Ctrl-D on unix as no other information is given.
There is a way to stop the Scanner at the end of the line. You need to define a delimiter that contains whitespace, the empty expression, but not the next line character:
public static void main(final String[] args) {
Scanner scan = new Scanner(System.in).useDelimiter(" *");
while (scan.hasNextInt() && scan.hasNext()) {
int x = scan.nextInt();
System.out.println(x);
}
}
This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.