String split gives array out of bounds - java

I am required to split a string which has been read from a external file. I have managed to split the string using this code;
String[] parts = line.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
Now when I attempt to access the data, part1 at index[0] works fine, however trying to get index [1] throw an index out of bounds exception. The data I'm trying to split looks like so
886.0452586206898 27115740907.871643
888.0387931034484 26218442896.246094
890.032327586207 25301777157.154663
892.0258620689656 24365534070.686035
894.0193965517242 23409502709.11487
Am I meant to remove white space before doing the string split?

Since i highly doubt that the index is getting lost. You might want to try this code to find out if the data is completly valid. If the error still occurs you might have the cause of the error at some different place, and want to show your actuall stacktrace.
while ((line = br.readLine()) != null) {
if(line.contains(".")) {
String[] parts = line.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
} else {
System.out.println("Corrupted data as: " + line);
}
}

I guess you are reading the file line by line, then you should split first against a "space" and then again the dot, otherwise you will get corrupted data...
886.0452586206898 27115740907.871643
as you can see, there are 2 elements in each line that can be split by dot

String[] parts = null;
String part1 = null;
String part2 = null;
System.out.println(parts[2]);
while ((line = br.readLine()) != null) {
System.out.println(line);
parts = line.split("\\.");
part1 = parts[0];
part2 = parts[1];
}
It is not working because you are trying to reach a variable that you declarated inside the while. Try to declarate outside it.

Do you want to extract each number from the input, then split on the decimal?
In that case, use Scanner to read in each number first, then split:
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String num = s.next();
String[] parts = num.split("\\.");
...
}

Related

Detect an array from text file

I have some files containing text, from which I have to extract some information, among which I have a 2-dimensional double array(sometimes it might be missing - therefore you'll find the "if" clause).
This is the way the file is formatted:
Name=fileName
groups={ group1=groupName group2=groupName minAge= maxAge= ages=[[18.0,21.0,14.7],[17.3,13.0,12.0]] }
I am using java.nio.file.Files, java.nio.file.Path and java.io.Bufferedreader to read these files, but I am having problems while trying to convert the Strings representing the arrays to real java Arrays:
Path p = Paths.get(filename);
try(BufferedReader br = Files.newBufferedReader(p)) {
String line = br.readLine();
String fileName = line.split("=")[1];
line = br.readLine();
String[] arr = line.split("=");
String group1 = arr[2].split(" ")[0];
String group2 = arr[3].split(" ")[0];
Integer minAge = Integer.parseInt(arr[4].split(" ")[0]);
Integer maxAge = Integer.parseInt(arr[5].split(" ")[0]);
double[][] ag = null;
if (line.contains("ages")) {
String age = arr[6].trim().replace("}", "").replace("[[", "").replace("]]", "").trim();
String[] arrAge = weights.split(",");
//don't know what to do here from now on, since the number of arrays inside
//the first one may vary from 1 to 2 (e.g I might find: [[3.0, 4.0]] or [[3.0, 7.0],[4.0,5.0]])
//this is what I was trying to do
ag = new double[1][arrAge.length];
for (int i = 0; i < arrAge.length; i++)
ag[0][i] = Double.parseDouble(arrAge[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
Is there any way to detect the array from the text without doing what I am trying to do in my code or is there any way to extract a correct 2-dimensional array by reading a file formatted that way?
One more question: is there a way to print a 2-dimensional array like that? If yes, how? (by using Arrays.toString I only get something like this: [[D#69222c14])
You can use regex to extract the two dimensional array from any string.
String groups="{ group1=groupName group2=groupName minAge= maxAge= ages=[[18.0,21.0,14.7],[17.3,13.0,12.0]] }";
String pattern = "(\\[\\[.+\\]\\])";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(groups);
if (m.find( ))
System.out.println(m.group());
The Output for the above code is:
[[18.0,21.0,14.7],[17.3,13.0,12.0]]

How to divide string by empty space in Java

So, I have the following situation:
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line= reader.readLine();
String first = ?
String second = ?
So, I know that user will enter something like this: love cats and dogs.
I want that the first word (in this case love) is always in String first and everything else in String second. How can I do it as simple as possible?
String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);
String first = parts[0];
String second = parts[1];
Simply:
int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);

Retrieving part of a string using a delimiter

Okay So I am creating an application but I'm not sure how to get certain parts of the string. I have read In a file as such:
*tp*|21394398437984|163600
*2*|AAA|1234567894561236|STOP|20140527|Success||Automated|DSPRN1234567
*2*|AAA|1234567894561237|STOP|20140527|Success||Automated|DPSRN1234568
*3*|2
I need to read the lines beginning with 2 so I done:
s = new Scanner(new BufferedReader(new FileReader("example.dat")));
while (s.hasNext()) {
String str1 = s.nextLine ();
if(str1.startsWith("*2*")) {
System.out.print(str1);
}
}
So this will read the whole line I'm fine with that, Now my issue is I need to extract the 2nd line beginning with numbers the 4th with numbers the 5th with success and the 7th(DPSRN).
I was thinking about using a String delimiter with | as the delimiter but I'm not sure where to go after this any help would be great.
You should use String.split("|"), it will give you an array - String[]
Try following:
String test="*2*|AAA|1234567894561236|STOP|20140527|Success||Automated|DSPRN1234567";
String tok[]=test.split("\\|");
for(String s:tok){
System.out.println(s);
}
Output :
*2*
AAA
1234567894561236
STOP
20140527
Success
Automated
DSPRN1234567
What you require will be placed at tok[2], tok[4], tok[5] and tok[8].
Just split the returned line based on your search, which would return an array of String elements where you can retrieve your elements based on their index:
s = new Scanner(new BufferedReader(new FileReader("example.dat")));
String searchLine = "";
while (s.hasNext()) {
searchLine = s.nextLine();
if(searchLine.startsWith("*2*")) {
break;
}
}
String[] strs = searchLine.split("|");
String secondArgument = strs[2];
String forthArgument = strs[4];
String fifthArgument = strs[5];
String seventhArgument = strs[7];
System.out.println(secondArgument);
System.out.println(forthArgument);
System.out.println(fifthArgument);
System.out.println(seventhArgument);

Split command on a nextElement

I am making a java servlet and am trying to make it display a preview of 3 different articles. I want it to preview the first sentence of each article, but can't seem to get split to work properly since I am reading the articles in with tokenizer. So I have something like:
while ((s = br.readLine()) != null) {
out.println("<tr>");
StringTokenizer s2 = new StringTokenizer(s, "|");
while (s2.hasMoreElements()) {
if (index == 0) {
out.println("<td class='first'>" + s2.nextElement() + "</td>");
}
out.println("</tr>");
}
index = 0;
}
How do I make s2.nextElement print out only the first sentence instead of the whole article? I imagine I could do split with a delimiter of ".", but can't get the code to work right. Thanks.
Try
s2.nextElement().split("\\.")[0];
to get the first sentence in the paragraph.
It would be better to use a Scanner:
Scanner scanner = new Scanner(new File("articles.txt"));
while (scanner.hasNext()) {
String article = scanner.next();
String[] parts = article.split("\\s*\\|\\s*");
String title = parts[0];
String text = parts[1];
String date = parts[2];
String image = parts[3];
String firstSentence = text.replaceAll("\\..*", ".");
// Output what you like about the article using the extracted parts
}
Scanner.next() reads in the whole line (the default delimiter is the newline char(s)).
split("\\s*\\|\\s*") splits the line on pipe chars (which have to be escaped because the pipe char has special regex meaning) and the \s* consumes any whitespace that may surround the pipe chars.
What I did was change hasMoreElements() to hasMoreTokens(). I then found the first occurrence of a ".". and created an int value. I then printed out a substring. here is what my code looked like:
while((s = br.readLine()) != null){
out.println("<tr>");
StringTokenizer s2 = new StringTokenizer(s, "|");
while (s2.hasMoreTokens()){
if (index == 0){
String one = s2.nextToken();
int i = one.indexOf(".");
out.println("<td>"+one.substring(0 , i)+"."+"</td>");
}

Buffered Reader find specific line separator char then read that line

My program needs to read from a multi-lined .ini file, I've got it to the point it reads every line that start with a # and prints it. But i only want to to record the value after the = sign. here's what the file should look like:
#music=true
#Volume=100
#Full-Screen=false
#Update=true
this is what i want it to print:
true
100
false
true
this is my code i'm currently using:
#SuppressWarnings("resource")
public void getSettings() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("FileIO Plug-Ins/Game/game.ini")));
String input = "";
String output = "";
while ((input = br.readLine()) != null) {
String temp = input.trim();
temp = temp.replaceAll("#", "");
temp = temp.replaceAll("[*=]", "");
output += temp + "\n";
}
System.out.println(output);
}catch (IOException ex) {}
}
I'm not sure if replaceAll("[*=]", ""); truly means anything at all or if it's just searching for all for of those chars. Any help is appreciated!
Try following:
if (temp.startsWith("#")){
String[] splitted = temp.split("=");
output += splitted[1] + "\n";
}
Explanation:
To process lines only starting with desired character use String#startsWith method. When you have string to extract values from, String#split will split given text with character you give as method argument. So in your case, text before = character will be in array at position 0, text you want to print will be at position 1.
Also note, that if your file contains many lines starting with #, it should be wise not to concatenate strings together, but use StringBuilder / StringBuffer to add strings together.
Hope it helps.
Better use a StringBuffer instead of using += with a String as shown below. Also, avoid declaring variables inside loop. Please see how I've done it outside the loop. It's the best practice as far as I know.
StringBuffer outputBuffer = new StringBuffer();
String[] fields;
String temp;
while((input = br.readLine()) != null)
{
temp = input.trim();
if(temp.startsWith("#"))
{
fields = temp.split("=");
outputBuffer.append(fields[1] + "\n");
}
}

Categories