JAVA- how to assign string value to string array dynamically - java

In my application i got string values dynamically. I want to assign these values to string array then print those values.But it shows an error(Null pointer exception)
EX:
String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
String st1 = null;
org.w3c.dom.Node nd = lst.item(s);
if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
NamedNodeMap nnm = nd.getAttributes();
for (int i = 0; i < 1; i++) {
st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
}
}
content[s] = st1;
//HERE it shows null pointer Exception.
}
Thanks

This is because your string array is null. String[] content=null;
You declare your array as null and then try to assign values in it and that's why it is showing NPE.
You can try giving initial size to your string array or better to use ArrayList<String>.
ie:
String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.
Better if you use arrayList like
List<String> content = new ArrayList<String>(); //-- no need worry about size.
For list use add(value) method to add new values in list and use foreach loop to print the content of list.

Use ArrayList or Vector for creating collection (or array) of strings in a dynamic fashion.
List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
contents.add(node.toString());
Outside the loop you can do as follows
for(String content : contents) {
System.out.println(content) // since you wanted to print them out

It's a little hard to understand what you're after because your example got munged. However, your String array is null. You need to initialize it, not just declare it. Have you considered using an ArrayList instead? Arrays in java are fixed length (unless they changed this since my university days).
ArrayList is a lot simpler to work with.
E.g.:
List<String> content = new ArrayList<String>();
for (int i = 0; i < limit; i++){
String toAdd;
//do some stuff to get a value into toAdd
content.add(toAdd)
}
There's also something weird with one of your for loops.
for(int i=0;i<1;i++)
The above will only ever iterate once. To clarify:
for(int i=0;i<1;i++){
System.out.println("hello");
}
is functionally identical to:
System.out.println("hello");
They both print out "hello" once, adn that's it.

Use
content[s] = new String(st1);
Now it creates new instance for that particular array index.

Related

for-each loop in java can't be used for assignments

Why for-each loop in java can't be used for assignments?
For eg I am trying the below example and not getting the expected result but compiles successfully:
int count = 0;
String[] obj = new String[3];
for (String ob : obj )
ob = new String("obj" + count++);
System.out.println(obj[0]); // null
ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.
Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it
String[] obj = { "obj1", "obj2", "obj3" };
or
for (int count = 0; count < obj.length; count++) {
obj[count] = "obj" + count;
}
As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.
Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:
String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray();
This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

How to solve Null Pointer Exception while using array?

Here its showing null pointer exception in the line arr[i] = "true";
String[] count = null;
String[] arr = null;
int i = 0;
rs2 = st2.executeQuery("SELECT COUNT(*) as y FROM " + usrtbl + " WHERE user_id NOT IN (SELECT user_id FROM " + usrroletbl + ")");
rs2.next();
if (rs2.getInt("y") == 0) {
arr[i] = "false";
count = arr;
i++;
} else {
arr[i] = "true";
count = arr;
i++;
}
Any help will be appreciated.
You need to initialize the String[] array
Approach 1
String[] errorSoon = new String[100]; // <--initialized statement, this is fixed size array, so you need to set the size accordingly, keeping memory usage in mind.
Approach2
use List
List<String> errorSoon = new ArrayList<String>();
Also as mentioned by #dave, if it is really required to have array here, or just a boolean variable can work for you.
You have defined arr to be null and you have not allocated it any memory. So of course, accessing arr[i] will result in a NullPointerException.
You could first run an SQL query to get the number of results and allocate the space, eg.
arr = new String[<count>];
Or you could use an ArrayList to hold the values. This is simpler as it will grow dynamically to hold your data.
As an aside, you should consider converting arr (or your ArrayList) to hold boolean. Then you can use true and false directly (rather than their string equivalents).
As #Dave said you have declared both the String arrays as null, so of course you will get NullPointerException. You have to know the size of your resultset first and then declare the array according to the size.
But instead of that I would recommend you to use ArrayList. Its simple and can dynamically add your result. You can do something like this-
List<String> list=new ArrayList<String>();
while(rs.next()){
if(// your condition){
list.add("something");
}
else{
list.add("something");
}
}
So it will keep on adding "something" in the list till the last row is covered.
Then you can easily iterate through the list as per your requirement.
Or you can also convert the ArrayList into an Array using the following command-
Object obj[]=list.toArray(); //Note that it will create an Array of Object datatype. You have to typecast it to your required datatype later if you want to print or manipulate the data.

Creating variables inside for loop when size of list is unknown

I apologize in advance if this question is stupid but I'm working on something at the moment which required me to implement a loop to parse through a List of objects of type MenuItem. Inside the loop I need to store the name of the object in a String variable.
However I am unsure about how many items will be in the List and therefor do not know how many variables I require. Can I somehow declare variables on the fly inside of the loop???
Below is my current code:
for(int i = 0; i != orderItems.size(); i++){
MenuItem item = orderItems.get(i);
String itemName = item.getName();
}
The reason for the loop above is because when it exits I want to send all of the itemName variables to a db via a Http post request. So I can pass as a parameter like this:
new RequestTask().execute(url, itemName1, itemName2, itemName3);
Any help would be much appreciated!
You can use varargs to specify a method that accepts a list of variables. In the end it is just a method that accepts an array of such variables. So you will end with
new RequestTask().execute(url, items); // items is String[]
If you do not know a priori the number of Strings, store them in a List. You then can get the number of items in the list, create an array big enough and fill it. Or, use the method toArray that will do just that.
Here is the ArrayList syntax I use all the time when looping on an unknown value. I then convert it to a normal array for further processing.
List<String> itemNameList = new ArrayList<String>();
for(int i = 0; i != orderItems.size(); i++) {
MenuItem item = orderItems.get(i);
itemNameList.add(item.getName());
}
String[] itemNameArray = new String[itemNameList.size()];
itemNameList.toArray(itemNameArray);
Put them into a list of some sort ie;
ArrayList<String> itemNameList = new ArrayList<String>();
for(int i = 0; i != orderItems.size(); i++){
MenuItem item = orderItems.get(i);
String itemName = item.getName();
itemNameList.add(itemName);
}

Try to create a 2D ArrayList in Java

I am trying to read in a file. I want to store the contents of the file in a 2D arraylist, where each place in the list holds one character. I want it so that each line in the original text file is one row in the array list. For instance if the input from the text file was:
a,b,c
d,e,f
g,h,i
then the array would hopefully look like:
{[a,b,c],[d,e,f],[g,h,i]}. Unfortunately at the moment my outcome is just [a,b,c,d,e,f,g,h,i].
Any ideas would be appreciated, I am new to Java. Thanks.
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Coursework1
{
public static void main(String[] args)
{
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0;i<firstDimension.length;i++) {
for (int j=0;j<firstDimension[i].length;j++) {
System.out.println(firstDimension[i][j]);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
your answer is actually correct and fully functioning. Your test code is just wrong as it puts too many new lines in.
for (int i=0;i<firstDimension.length;i++)
{
System.out.println();
for (int j=0;j<firstDimension[i].length;j++)
{
System.out.print(firstDimension[i][j]);
}
}
It seems that you don't fully understand the difference between an array and an array list.
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. So you have to know the size before you create it or you have to create it of a sufficient size.
On the other hand, ArrayList is a collection (complex type, see this tutorial for more information) which can hold simple objects, collections,... ArrayList can be imagined as a dynamic array - you don't have to know the initial size, it is automatically resized if you add or remove elements from it.
It is a good habit to iterate over the ArrayList like this
List<String> names = new ArrayList<String>();
// add something
// foreach loop
for (String name : names) {
// here you have access directly to the value
// and you don't have to write list.get(index)
System.out.println(name);
}
Now to you question. If you read the link above you should be able to construct it by yourself. But if you still don't know:
List<List<String>> twoDimensionList = new ArrayList<List<String>>();
Iteration with foreach loop
for (List<String> innerList : twoDimensionList) {
for (String value : innerList) {
...
}
}
You can embed Lists within Lists like:
List<List<String>> matrix = new ArrayList<List<String>>();
Then accessing elements you'd do,
matrix.get(1).get(2);
EDIT: I would also suggest you think more about if you want an Array or an ArrayList. They're not the same. An array list is resizable (you can keep appending more and more elements onto it, you're not forced to only have so many elements in the array list. This allows you to do things like have a List<List<String>> object where not every second dimension is the same length. Arrays on the other hand have a specific size associated with them, which would enable you to enforce that all rows have the same length, and all columns have the same height...
Your code works, you're just printing out the results wrong. Try:
for (int i = 0; i < firstDimension.length; i++)
{
for (int j = 0; j < firstDimension[i].length; j++)
{
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
This prints the chars from the same line on, well, the same line...
Each line (String) is already a list of characters with methods that let you iterate over it (length, charAt). So depending on what you are trying to achieve a list of strings may be enough.

Can't i initialized empty String array and pass in the value afterwards in Java?

I can't seems to find out what what is wrong with my codes? i can't pass in non-empty String value into an empty String array?
String[] profiles = wifiPositioningServices.GetAllProfileData();
ArrayList<String[]> macAddresses = new ArrayList<String[]>();
String[] macAddressTemp=null;
//store all profile data into a ArrayList of Profile objects
for(int i=0; i<profiles.length; i++){
String[] result = profiles[i].split(",");
Profile profile = new Profile();
profile.setProfileName(result[0]);
profile.setOwner(result[1]);
profile.setMap(result[2]);
profile.setVisible(result[3]);
boolean visible = Boolean.valueOf(result[3]);
if(visible){
//if visible is true, then add profile name and mac filters into arraylist
profileNames.add(result[0]);
int cnt=0;
for(int j=4; j<result.length; j++){
profile.setMacFiltersList(result[j]);
Log.e("Text:", result[j]);
macAddressTemp[cnt] = result[j];
++cnt;
}
macAddresses.add(macAddressTemp);
}
profileList.add(profile);
}
Java show a nullpointer exception at the line "macAddressTemp[cnt] = result[j];". I am sure that result[j] is not empty cause i was able to print it out via the log msg.
Use an ArrayList instead.
ArrayList<String> macAddressTemp = new ArrayList<String>(100); //check capacity
macAddressTemp.add(result[j]);
EDIT:
You changed your code wrong.
This ArrayList<String[]> macAddresses = new ArrayList<String[]>(); is creating a List that contains arrays. You have to create a List that contains String. Check the code above.
The array macAddressTemp is null.
The NPE is thrown because macAddressTemp is null. You probably want to declare and initialize macAddressTemp inside of the outer loop.
You explicitly set it to null:
String[] macAddressTemp=null;
You need to allocate some space for the array, or use a collection.

Categories

Resources