Can you use split and nextLine? - java

Let's say I had a scanner "in" that was assigned a one line CSV file, and I wanted to assign the values to an array, would I be able to do something like
String[] array = in.nextLine().split(",");

Yes, as noted in the comments. But you can also do this either reading from a string or from a file.
set the delimiter to match on 0 or more spaces, followed by a , followed by 0 or more spaces.
Scanner scanner = new Scanner("This, is , a ,test");
scanner.useDelimiter("\\s*,\\s*");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
prints
This
is
a
test

Related

Splitting a text file at regular expressions and creating an array

I need some help with a splitting a text file with java. I have a text file with around 2000 words, the text file is in the format as follows -
"A", "HELLO", "RANDOM", "WORD"... etc
My goal is to put these words into a string array. Using the scanner class I'm taking the text and creating a string, then trying to split and add to an array as follows.
Scanner input = new Scanner(file);
while(input.hasNext()){
String temp = input.next();
String[] wordArray = temp.split(",");
}
After added to the array, when I want to use or print each element, they are stored with the "" surrounding them. Instead of printing
A
HELLO
RANDOM
… etc they are printing
"A"
"HELLO"
"RANDOM"
So my question is how can I get rid of these regular expressions and split the text at each word so I'm left with no regular expressions?
Many Thanks
Try this
List<String> allMatches = new ArrayList<>();
Scanner input = new Scanner(new File(FILE_PATH), StandardCharsets.UTF_8);
while(input.hasNext()){
String temp = input.next();
Matcher m = Pattern.compile("\"(.*)\"").matcher(temp);
while (m.find()) {
allMatches.add(m.group(1));
}
}
allMatches.forEach(System.out::println);
Just in your case, when you have all values like this "A", "HELLO", "RANDOM", "WORD"... etc, where every value have delimiter ", ", you can use this temp.split("\", \""); and you don't need to use loop.
Use this to replace all occurrences of " with an empty string.
wordArray[i].replaceAll("/"", "");
Perform this in a loop.

Using Scanner hasNext() and hasNextLine() to retrieve 2 elements per line

In Java, if you were given a text file with two elements per line, how can we grab those elements separately?
For example say we have a 5 line text file with the following:
a morgan
b stewart
c david
d alfonso
e brittany
and let's say we want to store the single char in a variable and the name in another variable. How do we do this is java?
I have implemented some code somewhat like this:
while(scanner.hasNextLine()){
for(int i = 0; i < 2; i++){
char character = scanner.hasNextChar(); // doesn't exist but idk how
String name = scanner.hasNext();
}
}
Basically I have a while loop reading each 2 elements line by line and in each line there is a for loop to store each element in a variable. I am just confused on how to extract each separate element in java.
Considering that you're using scanner.hasNextLine() as your loop condition. You can split the String then collect the result as needed.
while (scanner.hasNextLine()){
String[] result = scanner.nextLine().split(" ");
char character = result[0].charAt(0);
String name = result[1];
}
You can split the line with the whitespace character by using the String.split(String regex) method.
It will produce an array of two String.
If you invoke while(scanner.hasNextLine()){ to get an input, you should invoke String name = scanner.nextLine(); to retrieve the input.
The hasNext() method returns a boolean to indicate if this scanner has another token in its input.
Doing while(scanner.hasNextLine()){ and scanner.hasNext() is redundant.

How to escape semicolon in Java Scanner

I'm trying to take an input using Scanner class in Java.
My code is:
Scanner scan = new Scanner( System.in);
String newline = scan.next();
My input is something like:
india gate;25;3
and I'm trying to replace the whole string above with a new string:
new delhi;23;2
using
.replace(str1, str2)
The problem is it's only replacing the first word in the string and the output is something like:
india delhi;25;3
How can I take it as a whole string using Scanner?
Use ; as delimiter like this
while (scanner.hasNextLine()) {
lineScanner = new Scanner(scanner.nextLine());
lineScanner.useDelimiter(";");
String article = lineScanner.next();
// and so on...
}
use .replaceAll("india gate;25;3", "new delhi;23;2");
output
new delhi;23;2
You should read up on how the Scanner class works. Basically by default, it uses whitespace as the delimiter for next(). This means that when you call next(), it reads until it finds whitespace, then it returns what it read. So when you call next() on "india gate;25;3", it reads "india" and then hits a space. So it returns you "india". If you want to read until a newline instead (which it looks like you do), you want to use nextLine().

Read a csv-file value by value with Scanner, useDelimiter(";") not working

I am trying to read a CSV file value by value using Scanner.useDelimiter(";").
However Scanner.nextLine() still returns the whole line instead of a single Value.
The CSV-file looks like this:
0.00034;0.1;0.3;0.6;1,00E-13
My code:
Scanner iStream = new Scanner(new InputStreamReader(new FileInputStream(file.cvs);
iStream.useDelimiter(";");
String[] test = new String[5];
for (int i = 0; i < 5; i++) {
test[i] = iStream.nextLine();
}
Result:
"0.00034;0.1;0.3;0.6;1,00E-13"
Expected Result:
"0.00034", "0.1", "0.3", "0.6", "1,00E-13"
Is this possible, or should I use String.split()?
Am I missing something?
Apart from the fact that this problem is ready-made for a parsing library such as OpenCSV, nextLine doesnt account for delimiter patterns. Use next instead
test[i] = iStream.next();
From the Java Scanner documentation:
public String next()
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches the delimiter pattern.
This literally answers your question. However, I am not sure about next's behaviour at the start and end becuase it has to be "preceded and followed" by the delimiter. Maybe someone can fill in on this?
You could add extra characters to your delimiter, like \netc.

Splitting strings with spaces

So I take in a line from a .txt file and turn it into a string. I would like to split the string up by |, but I also have spaces before and after it that is messing with the code, here is what I have so far:
File file = new File(fileLocation);
Scanner sc = new Scanner(file);
String line;
String[] words;
while(sc.hasNext()){
line = sc.next();
words = line.split("\\|");
this.german.add(words[0]);
this.english.add(words[1]);
}
An example line would be something like: in blue|in blau
I would also like to keep the spaces.
The .txt file would be:
in Rot|in red
in Blau|in blue
in Grun|in green
in Gelb|in Yellow
It would add all the items on the left of the | to the german list, and all of the ones on the right to the english list.
Ah, figured it out, the sc.next() is the next String, not the next line, I replaced it with sc.nextLine() and everything worked, thanks.
Call
line.replaceAll(" ", "");
beforehand; this will get rid of all the spaces. If you only want leading and trailing spaces from the split strings removed, use
words[i].trim()
instead.
Use the following pattern:
words = line.split("\\s+\\|\\s+");

Categories

Resources