I wanted to store a value from a string array to another string array. But I get "NullPointerException" error with the code below. "imagesSelected" is a string array stored with values inside. But when i wanted to move it into another string array after substring, I get error. I believed is because of the last line of code. I'm not sure how to make it work.
String[] imageLocation;
if(imagesSelected.length >0){
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
You need to do something like this:
String[] imageLocation = new String[imagesSelected.length];
Otherwise imageLocation will be null.
By the way, you don't need the if around your loop. It's completely redundant, as that will be the same logic that will be used at the start of the loop.
imageLocation[i]
have you initialized imageLocation?
I believe this error is because you are trying to point to a location in the string array that does not exist. imageLocation[0,1,2,3...etc] do not exist yet because the string array has not been initialized.
Try String[] imageLocation[however long you want the array to be]
You must allocate memory for imageLocation.
imageLocation = new String[LENGTH];
Your final solution code should be like as below, or compiler will give you an error that imageLocation may not have been initialized
String[] imageLocation = new String[imagesSelected != null ? imagesSelected.length : 0];
if (imagesSelected.length > 0) {
for (int i = 0; i < imagesSelected.length; i++) {
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
look at this code
String[] imageLocation;
if(imagesSelected.length >0){
imageLocation = new String[imageSelected.length];
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
Related
I have String Array of a good couple hundred lines of code. I have two other String Arrays, one with values I want to replace, and the other with the value I want it to replace to. I need to go through each line of the original code and check each line if it contains anything that I need to replace, and if it does, replace it. I want to replace it to a totally different String Array, so that the original is still left unchanged. This is what I have, but it's not exactly working.
for(int i=0; i<originalCode.length; i++) {
if( originalCode[i].contains("| "+listOfThingsToReplace[i]) ) {
newCode[i]=originalCode[i].replaceAll(("| "+listOfThingsToReplace[i]), ("| "+listOfReplacingThings[i]));
}
}
Obviously I need more counting variables somewhere (especially because originalCode.length !=listOfThingsToReplace.length), but I can't figure out where. Would I need more for loops? I tired doing that... but "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"... Any help please?
I think this should do the trick if I'm understanding the problem correctly
// New Code Array
String[] newCode = new String[originalCode.length];
for (int i=0; i<originalCode.length; i++) {
// New Code Line
String newCodeLine = originalCode[i];
// Iterate through all words that need to be replaced
for (int j=0; j<listOfThingsToReplace.length; j++) {
// String to replace
String strToReplace = listOfThingsToReplace[j];
// String to replace with
String strToReplaceWith = (j >= listOfReplacingThings.length) ? "" : listOfReplacingStrings[j];
// If there is a string to replace with
if (strToReplaceWith != "") {
// then replace all instances of that string
newCodeLine = newCodeLine.replaceAll(strToReplace, strToReplaceWith);
}
}
// Assign the new code line to our new code array
newCode[i] = newCodeLine;
}
I need to get textbox value into array and convert them into integer.
I'm not sure whether should I 1st convert and get into array or get into array and after convert.
Please explain with relevant examples
I've already tied out this code segment. But its wrong according to my knowledge.
String data [] = Integer.parseInt(jTextField1.getText());
String[] stringValues = jTextField1.getText().split("[,]");
int[] numArray= new int[stringValues.length];
for(int i=0; i<numArray.length; i++){
numArray[i]= Integer.parseInt(stringValues[i]);
}
You are trying to assign an single inter to a string array so it will not work.
Because two types are incompatible.
Either you must have an integer array or you can have string array and use string value of the textfield.
e.g.
String []stringData = {jTextField1.getText()};
or
int [] = {Integer.parseInt(jTextField1.getText())};
But since you are using just single value it is better to use an variable rather than an array.
Try this:
String str = "34,56,78,32,45";
String[] parts = str.split(",");
for (int i = 0; i < parts.length; i++)
{
int no=Interger.parse(parts[i]);
//Do your stuff here
}
I am getting an error when trying to use a JFileChooser to scan a text file add it to an array and parse one of the strings to a double and two to integers. Does it have to do with the fact that the addEmployee method adds the six parameters to an arrayList? Here is the code...
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
String[] rowData = scan.next().split(":");
if(rowData.length == 5){
rowData[4] = null;
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
else{
fName = rowData[0];
lName = rowData[1];
position2 = rowData[2];
firstParam = Double.parseDouble(rowData[3]);
secondParam = Integer.parseInt(rowData[4]);
empNum = Integer.parseInt(rowData[5]);
}
if (position2.equals("Manager")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else if(position2.equals("Sales")){
c.addEmployee(fName, lName, position2, firstParam, 0, empNum);
}
else{
c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);
}
}
}
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
You are trying to fetch empNum = Integer.parseInt(rowData[5]);
row data only having size 5 that means index 0-4, Thats why ArrayIndexOutOfBoundsException is getting
So Initialize String[] rowData = new String[6];
String[] rowData = new String[5]; // edited out of original post
rowData = scan.next().split(":");
The first statement allocates an array of 5 Strings and sets them all to null. The second statement just throws away the array you just allocated. The result of split will return an array of however many items it finds, and then you assign rowData, which is a reference to an array, to a reference to the new array. The old one gets garbage collected. So there's no guarantee that rowData will have 5 elements after this assignment.
You'll have to decide what you want to do if the split doesn't return enough array elements. You could use something like Arrays.copyOf that could put the split result into some of the rowData elements while leaving the rest alone, but then the unassigned elements will still be null, and you'll just get a NullPointerException a few lines later. So you have some design decisions to make here.
More: You may want to consider using the Scanner method nextLine() instead of next(). next() will return just one token, which means it will stop at a space character, which means you will have problems if someone is named "Mary Beth" or something like that.
It appears to me that there could be a better way to this, maybe using loops, I think.
String hora1 = listaH.get(0);
String hora2 = listaH.get(1);
String hora3 = listaH.get(2);
String hora4 = listaH.get(3);
String hora5 = listaH.get(4);
String hora6 = listaH.get(5);
String hora7 = listaH.get(6);
String hora8 = listaH.get(7);
String hora9 = listaH.get(8);
Is there another way to write this using less words?
Thanks
It depends on what you want to achieve and what you hope to gain from it...but...
Assuming that listaH is java.util.List, you could use
for (String horse : listaH) {
System.out.println(horse);
}
(NB: You can do the same thing with arrays)
Take a look at The for statement and The while and do-while statements for more details
Use arrays for hora variable. It can be like
String[] hora = new String[9];
Now you can use any loops, but for is best for your case.
for(int i = 0; i < 9 ; i++){
hora[i] = listaH.get(i);
}
But why waste resource and complexity on new variables? You can do something like listaH.get(4) wherever you need hora5.
Iterator itr = listaH.iterator();
while(itr.hasNext()) {
String element = (String) itr.next();
System.out.print(element + " ");
}
or
for (int i=0;i<listaH.size();i++) {
String element = (String)listaH.get(i);
System.out.print(element + " ");
}
if you need String array then use this one
String[] array = listaH.toArray(new String[listaH.size()]);
Yes. Instead of separate variables for each element, you should just leave them in the original list and then access them that way. So, for example, when you need the value that you are trying to store in hora9, use listaH.get(8) instead.
I have a piece of code
for(int i = 0; i < num_of_random; i++){
String str = in.readLine();
if(str != null){
String[] randoms = new String[4];
randoms = str.split(",");
dateRanges[i] = Integer.parseInt(randoms[0]);
id[i] = Integer.parseInt(randoms[1]);
flag[i] = Integer.parseInt(randoms[2]);
system[i] = Integer.parseInt(randoms[3]);
}
}
When I run this code against findBugs, I get a suggestion for
"String[] randoms = new String[4];"
This instruction assigns a value to a local variable, but the value is not read or used in any subsequent instruction. Often, this indicates an error, because the value computed is never used.
Why do I get this?
Thanks a lot
Because you initialize a variable to a value (new String[4]), and then replace the variable value with another one (the result of str.split(",")) just after. The initialization is thus not necessary.
Your code is functionally equivalent to
String[] randoms = str.split(",");
except it allocates a new String array which is immediately discarded.
Because you can simply do this:
String[] randoms = str.split(",");
Try directly:
String[] randoms = str.split(",");
You don't need to instanciate a String[], the split method already does it.
This is an example of the technique that I call The I'm dumb technique.
Typically it is the result of a programmer writing code, but not understanding what they are doing. At some point the programmer read or heard something like this: "you must initialize all local variables!". When they wrote the code String[] randoms that popped into their head so they added = new String[4].
A more seasoned programmer might look at that and think I used to be dumb, but not any more! Lets move the variable declarations out of the loop and produce something like this:
String str;
String[] randoms;
for(int index = 0; index < num_of_random; ++index)
{
str = in.readLine();
if (str != null)
{
randoms = str.split(",");
dateRanges[index] = Integer.parseInt(randoms[0]);
id[index] = Integer.parseInt(randoms[1]);
flag[index] = Integer.parseInt(randoms[2]);
system[index] = Integer.parseInt(randoms[3]);
}
}