I'm working on a little server app with Java. So, I'm getting informations from different client, and if information comes in, the following method is called:
public void writeToArray(String data) {
data = trim(data);
String[] netInput = new String[5];
netInput[0]="a";
netInput[1]="a";
netInput[2]="a";
netInput[3]="a";
netInput[4]="a";
netInput = split(data, ",");
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]); // THIS LINE KICKS OUT THE ERROR.
if(pos_arr >0 && pos_arr<100) {
fernrohre[pos_arr] = rohr_value;
println("pos arr length: " + fernrohre[pos_arr]);
println("pos arr: " + pos_arr);
}
The console on OS X gives me the following error:
Exception in thread "Animation Thread"
java.lang.ArrayIndexOutOfBoundsException:1
at server_app.writeToArray(server_app.java:108) at server_app.draw(server_app.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:1606)
at processing.core.PApplet.run(PApplet.java:1503)
at java.lang.Thread.run(Thread.java:637)
As you can see, I tried to fill the array netInput with at least 5 entries, so there can't be an ArrayIndexOutOfBoundsException.
I don't understand that, and I'm thankful for your help!
It would work already for me, if I can catch the error and keep the app continuing.
You put 5 Strings into the array, but then undo all your good work with this line;
netInput = split(data, ",");
data obviously doesn't have any commas in it.
In this line
netInput = split(data, ",");
your array is being reinitialized. Your split method probably returns an array with only 1 element (I can guess that data string doesn't contain any ",").
Update
The split() method is custom, not String.split. It too needs to be checked to see what is going wrong. Thanks #Carlos for pointing it out.
Original Answer
Consider this line:
netInput = split(data, ",");
This will split the data string using comma as a separator. It will return an array of (number of commas + 1) resulting elements. If your string has no commas, you'll get a single element array.
Apparently your input string doesn't have any commas. This will result in a single element array (first element aka index = 0 will be the string itself). Consequently when you try to index the 2nd element (index = 1) it raises an exception.
You need some defensive code,
if(netInput.length > 1)
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]);
You make
netInput = split(data, ",");
and
split(data, ",");
returns one element array
You are re-assigning your netInput variable when the split() method is called.
The new value might not have an array count of 5.
Can you provide the source for the split() method?
Related
I've read in other posts, that instead of writing just System.out.println(finalPressedKey);
you should write System.out.println(Arrays.toString((finalPressedKey)); because otherwise it will just return the location where the String is saved (as far as I understood it).
public static String PressedKey[] = new String[2000];
public static String[][] finalPressedKey = {{ "", "", "", "", "", "", "", "", "", "", "", "" }}; // 12
public static String FPK3;
public static void upcounter(KeyEvent e) {
for (int x = 0; x < PressedKey.length; x++) {
if (PressedKey[x] != null && PressedKey[x + counter] != null) {
//FPK counter is supposed to be a line, and counter is where the words are supposed to be saved
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
System.out.println(Arrays.toString(finalPressedKey));
}
}
Whenever I Press a Button, it should be saved in my PressedKey Array, and finalPressedKey is supposed to contain itself, and PressedKey (also , only the last element of the array is supposed to be printed), but instead it just prints [[Ljava.lang.String;#76f42c4b]
I also tried using Arrays.deepToString(); but it gives me the same output as with Arrays.toString();
Thanks for your help!
A String[][] is not a 2-d array. It is an array of String[]. The difference is subtle but important.
The method Arrays.toString() takes an array, iterates through its elements, calls toString() on all of them, and adds a prefix, suffix, and delimiters. Since you give it a String[][] (an array of String[]), it will do the following:
Iterate through the elements (each of them a String[])
call toString() on each element - giving the default toString() value of an array - i.e. its memory address (not really but for this purpose it doesn't matter)
concatenate
Luckily for you, there is an easier way - just use Arrays.deepToString(). This behaves as you would expect.
I did not understand the whole code, but following statement is very suspicious:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];
since it is adding an array (finalPressedKey[...]) to a string (PressedKey[...]), which will result in that strange text - the standard textual representation of an array (returned by toString). (from a mathematical point of view, it's strange to have 2 indexes )2D_ before the assignment and only one on the right side (1D) for same matrix)
I'm not sure, since we cannot see what counteris, but I believe you wanted something like:
finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter][counter] + PressedKey[x + counter];
that is, an additional [counter] on second line.
This can also be written as
finalPressedKey[FPKcounter][counter] += PressedKey[x + counter];
If you only want to store lines of strings, a normal String[] is good for you
finalPressedKey[FPKcounter] += PressedKey[x + counter];
even though I wouldn't recomment doing this, no matter what you're trying to accomplish, since this will create a new String object each time a key is pressed.
Maybe ask the question differently and tell us what you're trying to do. I guess String arrays might not be the way to go.
You have to print the elements of your array with
for(int i = 0; i<finalPressedKey[0].length; i++){
for(int j=0; j<finalPressedKey[1].length; j++){
System.out.println(finalPressedKey[i][j]);
}
}
if I understand it correctly.
I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.
You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps
If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}
I have the following issue: I am trying to parse a .csv file in java, and store specifically 3 columns of it in a 2 Dimensional array. The Code for the method looks like this:
public static void parseFile(String filename) throws IOException{
FileReader readFile = new FileReader(filename);
BufferedReader buffer = new BufferedReader(readFile);
String line;
String[][] result = new String[10000][3];
String[] b = new String[6];
for(int i = 0; i<10000; i++){
while((line = buffer.readLine()) != null){
b = line.split(";",6);
System.out.println("ID: "+b[0]+" Title: "+b[3]+ "Description: "+b[4]); // Here is where the outofbounds exception occurs...
result[i][0] = b[0];
result[i][1] = b[3];
result[i][2] = b[4];
}
}
buffer.close();
}
I feel like I have to specify this: the .csv file is HUGE. It has 32 columns, and (almost) 10.000 entries (!).
When Parsing, I keep getting the following:
XXXXX CHUNKS OF SUCCESFULLY EXTRACTED CODE
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:3
at ParseCSV.parseFile(ParseCSV.java:24)
at ParseCSV.main(ParseCSV.java:41)
However, I realized that SOME of the stuff in the file has a strange format e.g. some of the texts inside it for instance have newlines in them, but there is no newline character involved in any way. However, if I delete those blank lines manually, the output generated (before the error message is prompted) adds the stuff to the array up until the next blank line ...
Does anyone have an idea how to fix this? Any help would be greately appreciated...
Your first problem is that you probably have at least one blank line in your csv file. You need to replace:
b = line.split(";", 6);
with
b = line.split(";");
if(b.length() < 5){
System.err.println("Warning, line has only " + b.length() +
"entries, so skipping it:\n" + line);
continue;
}
If your input can legitimately have new lines or embedded semi-colons within your entries, that is a more complex parsing problem, and you are probably better off using a third-party parsing library, as there are several very good ones.
If your input is not supposed to have new lines in it, the problem probably is \r. Windows uses \r\n to represent a new line, while most other systems just use \n. If multiple people/programs edited your text file, it is entirely possible to end up with stray \r by themselves, which are not easily handled by most parsers.
A way to easily check if that's your problem is before you split your line, do
line = line.replace("\r","").
If this is a process you are repeating many times, you might need to consider using a Scanner (or library) instead to get more efficient text processing. Otherwise, you can make do with this.
When you have new lines in your CSV file, after this line
while((line = buffer.readLine()) != null){
variable line will have not a CSV line but just some text without ;
For example, if you have file
column1;column2;column
3 value
after first iteration variable line will have
column1;column2;column
after second iteration it will have
3 value
when you call "3 value".split(";",6) it will return array with one element. and later when you call b[3] it will throw exception.
CSV format has many small things, to implement which you will spend a lot of time. This is a good article about all possible csv examples
http://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules_and_examples
I would recommend to you some ready CSV parsers like this
https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVParser.html
String's split(pattern, limit) method returns an array sized to the number of tokens found up to the the number specified by the limit parameter. Limit is the maximum, not the minimum number of array elements returned.
"1,2,3" split with (",", 6) with return an array of 3 elements: "1", "2" and "3".
"1,2,3,4,5,6,7" will return 6 elements: "1", "2", "3", "4", "5" and ""6,7" The last element is goofy because the split method stopped splitting after 5 and returned the rest of the source string as the sixth element.
An empty line is represented as an empty string (""). Splitting "" will return an array of 1 element, the empty string.
In your case, the string array created here
String[] b = new String[6];
and assigned to b is replaced by the the array returned by
b = line.split(";",6);
and meets it's ultimate fate at the hands of the garbage collector unseen and unloved.
Worse, in the case of the empty lines, it's replaced by a one element array, so
System.out.println("ID: "+b[0]+" Title: "+b[3]+ "Description: "+b[4]);
blows up when trying to access b[3].
Suggested solution is to either
while((line = buffer.readLine()) != null){
if (line.length() != 0)
{
b = line.split(";",6);
System.out.println("ID: "+b[0]+" Title: "+b[3]+ "Description: "+b[4]); // Here is where the outofbounds exception occurs...
...
}
or (better because the previous could trip over a malformed line)
while((line = buffer.readLine()) != null){
b = line.split(";",6);
if (b.length() == 6)
{
System.out.println("ID: "+b[0]+" Title: "+b[3]+ "Description: "+b[4]); // Here is where the outofbounds exception occurs...
...
}
You might also want to think about the for loop around the while. I don't think it's doing you any good.
while((line = buffer.readLine()) != null)
is going to read every line in the file, so
for(int i = 0; i<10000; i++){
while((line = buffer.readLine()) != null){
is going to read every line in the file the first time. Then it going to have 9999 attempts to read the file, find nothing new, and exit the while loop.
You are not protected from reading more than 10000 elements because the while loop because the while loop will read a 10001th element and overrun your array if there are more than 10000 lines in the file. Look into replacing the big array with an arraylist or vector as they will size to fit your file.
Please check b.length>0 before accessing b[].
Im working with flying saucer and want to export an xhtml to an pdf.
Everything works fine, but now I want to add an empty column, for example for descriptions or something.
I want to create a method addColumn(). which should add in every row of the table at the end a new, empty cell.
I tried following code:
String[] arr = content.split("<td");
String test = "";
for (int i = 0; i < arr.length; i++) {
if(i != 0){
arr[i] = "<td" + arr[i];
test += arr[i];
}
}
This should split the content on every beginning "td" tag.
String.split("<td") removes the "<td" from the content so i want to add it again.
But if i compare those:
if(test.equalsIgnoreCase(content)){
System.out.println("SUCCESS");
}
else{
System.out.println("FAIL");
}
I always fail.
Just help me to get the right content back out of the array, this would make me go a step in the right direction!
Thank you.
Try to replace your split line with this:
String[] arr = content.split("<td", -1);
Otherwise you will loose some input in arr, see the split(String) API doc:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The added -1 makes sure that your content can also contain "<tr" at its beginning, for example. See the split(String, int) API doc for further explanations.
I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?
You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();
You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.