Java input parsing with delimiter | (pipe) - java

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

Related

Converting String returned from Scanner nextLine() to String array

My requirement is that I need to convert a string input taken from a Scanner's nextLine() method, to a string array:
My code:
Scanner sc= new Scanner(System.in);
String myString = sc.nextLine();
The above code works fine, when I give input in the console as : new String[]{"A:22","D:3","C:4","A:-22"}
but my challenge is to read scanner input and assign it to String array like this:
String[] consoleInput=sc.nextLine();
I have an incompatible type error, which is normal as String cannot be converted to String array. Is there a way to convert sc.nextLine() to String array in the above line?
If you literally type n, e, w, , S, etcetera (you type in new String[] {"A:22", "D:3"} and you want a method on scanner such that you get a string with that data), that is incredibly complicated and involves linking a java compiler in. If you're asking this kind of question, likely well beyond your current skill level.
What you can do, however, is simply ask the user to enter something like:
A:22 D:3 C:4 A:-22
Simply .nextLine().split(" ") and voila: First read a line, then split that line into a string array by looking for spaces as separators.
Scanner sc = new Scanner(System.in);
String myString = sc.nextLine();
String[] arr = myString.replaceAll("[ \"{}]", "").split(",");
Explanation:
The regex in replaceAll replaces the characters ", {, '}, and ` (space character) with an empty string. Then you simply split the string along all the commas, and you get a String array containing all the tokens the user entered.
Note: the regex removes all spaces as well, so if your tokens have spaces in them, then they will get removed. However, from what I gathered from your question, there won't be any spaces in the elements of the array.
Modified the regex pattern in replaceAll() method :
String[] strArr = s.nextLine().replaceAll("[ \"{}\\]\\[(new|String)]", "").split(",");
Output on printing the String Array strArr:
A:22
D:3
C:4
A:-22

Multiple input.next() inside of a while(input.hasNext()) triggers NoSuchElementException in Java

I have a text file
Jim,A,94
Pam,B-4,120
Michael,CC,3
I want to save each token delimited by a comma to a string variable. I have this code:
File f = new File(filename);
Scanner input = new Scanner(f);
input.useDelimiter(",");
while (input.hasNext())
{
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
}
input.close();
But this keeps triggering NoSuchElementException. What am I doing wrong here?
This is a subtle quirk of how Scanner#next() works. That method looks for a "token", which is everything between occurrences of the delimiter character. The default delimiter is "\\p{javaWhitespace}+", which includes \n, \r.
You changed the delimiter to a comma, and ONLY the comma. To your Scanner the input looks like this:
Jim,A,94\nPam,B-4,120\nMichael,CC,3
The tokens as seen by your scanner are:
Jim
A
94\nPam
B-4
120\nMichael
CC
3
That's only 7 tokens, so you hit the end of input before satisfying all the next() invocations.
The simplest fix is to set the delimiter to "[," + System.lineSeparator() + "]".
However, Scanner is the cause of endless errors and frustration for new developers, and should be deprecated and banished (that won't happen because of the existing code base). What you should be doing is reading entire lines and then parsing them yourself.
You have a custom delimiter ,. So, your input string is delimitted by , and everything before and after that character will constitute a token returned by .next();.
\n escape character, that is present in your input as a new line character, is also a character:
\n (linefeed LF, Unicode \u000a)
and it's being read as part of your token.
Here is another way to achieve what you are trying to do:
File f = new File(filename);
Scanner input = new Scanner(f);
while (input.hasNext()) {
String[] sarray = input.nextLine().split(",");
for (String s : sarray ) {
System.out.println(s);
}
}
Of course, that can be improved, but basically I suggest that you use the Scanner to read the file line by line and then you split by comma delimiter.

Splitting a String in java at a tab

I am attempting to split a String into 2 separate Strings, one from the first letter up until a tab, and the other beginning after the tab and ending at the end of the String. I have looked over this post and have found my problem to be different. I am currently trying to utilize the split() method, but with no luck. My code is as follows:
Scanner loadFile = new Scanner(System.in);
loadFile = new Scanner(menuFile);
//loops through data and adds into the SSST
while(loadFile.hasNextLine()){
String line = loadFile.nextLine();
String[] thisLine = line.split(" ");
System.out.println(thisLine[0]);
String item = thisLine[0];
String value = thisLine[1];
menu.put(item, value);
I run into my problem at the line line.split(" "); because I do not know the argument to provide to this method in order to split at the tab in my String.
menu in this code is a separate object and is irrelevant.
Sample input for this program:
"baguette 400"
Desired output for this program:
String 1: "baguette"
String 2: "400"
The tab character is written \t. The code for splitting the line thus looks like this:
String[] thisLine = line.split("\t");
More flexible, if feasible for your use case: For splitting on generic white space characters, including space and tab use \\s (note the double reversed slash, because this is a regex).

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

Categories