How do I split an input string in Java? - java

User enters a string in java, I have to split it into different components.
Scanner scanner = new Scanner(System.in);
String test = scanner.next();
// split the test variable using the split method
String [] parts = test.split(" ,", 3);
s[i].setFirstName(parts[0].trim());
s[i].setlastName(parts[1].trim());
s[i].setID(Integer.parseInt(parts[2].trim()));
s[i].setgrade(Integer.parseInt(parts[3].trim()));
but it's not working. I can only get the first word to show up.

With your comment
I can get only one word to show up. it doesn't read any proceeding
words.
Use nextLine() instead of next().
next() will only return what comes before a space.
nextLine() automatically moves the scanner down after returning the current line.
name = scanner.nextLine();
Scanner doc

Use nextLine() rather than next() should fix the issue.
For further reference, take a look at the docs.

Change
String test = scanner.next();
to
String test = scanner.nextLine();
scanner.next() takes a word upto it encounters a blank space. nextLine() will consider the whole line.

Related

What is scanner skip in Java and why to use it?

scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
Can someone explain, what does the above code mean.
I'm pretty new to Java.
Any help would be greatly appreciated.
Scanner.skip
public Scanner skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters. This method will skip input if an anchored match of the specified pattern succeeds.
If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementException is thrown.
Since this method seeks to match the specified pattern starting at the scanner's current position, patterns that can match a lot of input (".*", for example) may cause the scanner to buffer a large amount of input.
So this allows you to "move" the scanner position using a regex.
Example :
Skip the start of the line :
Scanner scan = new Scanner("Hello world");
scan.skip("Hello ");
System.out.println(scan.nextLine());
scan.close();
world
Since this is using a regex, you skip until a work in the middle of a line :
Scanner scan = new Scanner("Hello world, I am happy to see you");
scan.skip(".*I am ");
System.out.println(scan.nextLine());
scan.close();
happy to see you
The skip() method of this class does exactly that. It will skip input matching the pattern. In this case, the pattern is saying to skip over carriage returns (\r) and new lines (\n), plus some unicode caracters.
So, when the line is read, it will ignore that pattern and return just the rest of the string. A simpler example would be like this. Let's say you have a string:
String s = "Hello world, this is my scanner!";
Then if you have a scanner such as:
Scanner scan = new Scanner(s);
scan.skip(", this is my scanner");
Then when you do:
System.out.println("" + scanner.nextLine());
The output to the console will be simply
Hello world!
What happened is the pattern ", this is my scanner" was matched, and ignored from the input. Then all that was left is the "Hello world!" string.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s = "Hello world, this is my scanner!";
//Then if you have a scanner such as:
Scanner scan = new Scanner(s);
scan.skip("world");
//Then when you do:
System.out.println("" + scan.nextLine());
scan.close();
}
}
Output: Exception thrown
When I passed Hello to scan.skip(), the code worked and printed everything past Hello.
You can only pass a prefix to .skip(). Don't pass a substring starting from anywhere in it. The string passed has to start the input/or the string S in this case.
Scanner scan = new Scanner(System.in);
scan.skip("a");
//Then when you do:
System.out.println("err");
System.out.println("" + scan.nextLine());
scan.close();
If I enter anything starting with a, it skips a and displays rest of the line.
However when I enter anything that doesn't start with a, Then following System.out.println() is never executed and I get stuck at the input. It won't take input.

Java input parsing with delimiter | (pipe)

I know pipe is a special character and I need to use:
Scanner input = new Scanner(System.in);
String line = input.next();
String[] columns = line.split("\\|");
to use the pipe as a delimiter. But it doesn't work as desired when I parse from the command line.
e.g.
When I parse from a file, this just works. However, when the input has a white space, whenever I parse the input from command line, it gives me out of bounds error, because it splits the word into two array element.
input
a|5|Hello|3
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "3";
bug:
input:
a|5|Hello World|3;
output:
columns[0] = "a";
columns[1] = "5";
columns[2] = "Hello";
columns[3] = "World";
columns[4] = "3";
I want columns[3] as "Hello World". How can I fix this?
I think you should get the data from user by using nextLine() instead of only next().
In my case its working fine just click here and check the source code ..
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line n).
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. Source
To overcome, you should use nextline() method instead.
String line = input.nextline();

How to split a string with space being the delimiter using Scanner

I am trying to split the input sentence based on space between the words. It is not working as expected.
public static void main(String[] args) {
Scanner scaninput=new Scanner(System.in);
String inputSentence = scaninput.next();
String[] result=inputSentence.split("-");
// for(String iter:result) {
// System.out.println("iter:"+iter);
// }
System.out.println("result.length: "+result.length);
for (int count=0;count<result.length;count++) {
System.out.println("==");
System.out.println(result[count]);
}
}
It gives the output below when I use "-" in split:
fsfdsfsd-second-third
result.length: 3
==
fsfdsfsd
==
second
==
third
When I replace "-" with space " ", it gives the below output.
first second third
result.length: 1
==
first
Any suggestions as to what is the problem here? I have already referred to the stackoverflow post How to split a String by space, but it does not work.
Using split("\\s+") gives this output:
first second third
result.length: 1
==
first
Change
scanner.next()
To
scanner.nextLine()
From the javadoc
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Calling next() returns the next word.
Calling nextLine() returns the next line.
The next() method of Scanner already splits the string on spaces, that is, it returns the next token, the string until the next string. So, if you add an appropriate println, you will see that inputSentence is equal to the first word, not the entire string.
Replace scanInput.next() with scanInput.nextLine().
The problem is that scaninput.next() will only read until the first whitespace character, so it's only pulling in the word first. So the split afterward accomplishes nothing.
Instead of using Scanner, I suggest using java.io.BufferedReader, which will let you read an entire line at once.
One more alternative is to go with buffered Reader class that works well.
String inputSentence;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
inputSentence=br.readLine();
String[] result=inputSentence.split("\\s+");
rintln("result.length: "+result.length);
for(int count=0;count<result.length;count++)
{
System.out.println("==");
System.out.println(result[count]);
}
}

Deliminter is not working for scanner

The user will enter a=(number here). I then want it to cut off the a= and retain the number. It works when I use s.next() but of course it makes me enter it two times which I don't want. With s.nextLine() I enter it once and the delimiter does not work. Why is this?
Scanner s = new Scanner(System.in);
s.useDelimiter("a=");
String n = s.nextLine();
System.out.println(n);
Because nextLine() doesn't care about delimiters. The delimiters only affect Scanner when you tell it to return tokens. nextLine() just returns whatever is left on the current line without caring about tokens.
A delimiter is not the way to go here; the purpose of delimiters is to tell the Scanner what can come between tokens, but you're trying to use it for a purpose it wasn't intended for. Instead:
String n = s.nextLine().replaceFirst("^a=","");
This inputs a line, then strips off a= if it appears at the beginning of the string (i.e. it replaces it with the empty string ""). replaceFirst takes a regular expression, and ^ means that it only matches if the a= is at the beginning of the string. This won't check to make sure the user actually entered a=; if you want to check this, your code will need to be a bit more complex, but the key thing here is that you want to use s.nextLine() to return a String, and then do whatever checking and manipulation you need on that String.
Try with StringTokenizer if Scanner#useDelimiter() is not suitable for your case.
Scanner s = new Scanner(System.in);
String n = s.nextLine();
StringTokenizer tokenizer = new StringTokenizer(n, "a=");
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
or try with String#split() method
for (String str : n.split("a=")) {
System.out.println(str);
}
input:
a=123a=546a=78a=9
output:
123
546
78
9

Scanner class skips over whitespace

I am using a nested Scanner loop to extract the digit from a string line (from a text file) as follows:
String str = testString;
Scanner scanner = new Scanner(str);
while (scanner.hasNext()) {
String token = scanner.next();
// Here each token will be used
}
The problem is this code will skip all the spaces " ", but I also need to use those "spaces" too. So can Scanner return the spaces or I need to use something else?
My text file could contain something like this:
0
011
abc
d2d
sdwq
sda
Those blank lines contains 1 " " each, and those " " are what I need returned.
Use Scanner's hasNextLine() and nextLine() methods and you'll find your solution since this will allow you to capture empty or white-space lines.
By default, a scanner uses white space to separate tokens.
Use Scanner#nextLine method, Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
To use a different token separator, invoke useDelimiter(), specifying
a regular expression. For example, suppose you wanted the token
separator to be a comma, optionally followed by white space. You would
invoke,
scanner.useDelimiter(",\\s*");
Read more from http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
You have to understand what is a token. Read the documentation of Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You could use the nextLine() method to get the whole line and not "ignore" with any whitespace.
Better you could define what is a token by using the useDelimiter method.
This will work for you
Scanner scanner = new Scanner(new File("D:\\sample.txt"));
while (scanner.hasNextLine()) {
String token = scanner.nextLine();
System.out.println(token);
}
To use a more funtional approach you could use something like this:
String fileContent = new Scanner(new File("D:\\sample.txt"))
.useDelimiter("")
.tokens()
.reduce("", String::concat);

Categories