Java NullPointerException in Array - java

I get an error when I do the following operation.
public static String text = "ng";
public static String[] specialConsonants = new String[4];
public static String[] specialConsonantsUni = new String[6];
public void setSpecial(){
specialConsonantsUni[0] = "ං";
specialConsonants[0] = "ng";
specialConsonantsUni[1] = "ඃ";
specialConsonants[1] = "h/g";
specialConsonantsUni[2] = "ඞ";
specialConsonants[2] = "N/g";
specialConsonantsUni[3] = "ඍ";
specialConsonants[3] = "R/g";
// special characher Repaya
specialConsonantsUni[4] = "ර්" + "\u200D";
specialConsonants[4] = "/R/g";
specialConsonantsUni[5] = "ර්" + "\u200D";
specialConsonants[5] = "/\\r/g";
}
public static void main(String args[]){
for (int i=0; i < specialConsonants.length; i++){
text = text.replace(specialConsonants[i], specialConsonantsUni[i]);
System.out.println(text);
}
}
I'm trying to create a locale app. So you may not see some fonts. The error is following.
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.replace(Unknown Source)
at in.isuru.srtuc.Stuff.main(Stuff.java:223)

specialConsonants and specialConsonantsUni are not initilized. You've just defined setSpecial() but not called it before doing replaces
The correct behavior would be:
public static void main(String args[]){
setSpecial();
for (int i=0; i < specialConsonants.length; i++){
text = text.replace(specialConsonants[i], specialConsonantsUni[i]);
System.out.println(text);
}
}
note also that setSpecial should be static in that case
Moreover you have to change dimension of specialConsonants to 6

Because specialConsonants[i] is null. You have not initialized it.
its like
specialConsonants = {null,null,null,null}
You need to make function setSpecial static then call it before the loop.

public static String[] specialConsonants = new String[4];
public void setSpecial(){
// ...
specialConsonants[5] = "/\\r/g";
}
specialConsonants is of array size 4. There is no 5th index for it. Also you haven't called the array initializer method.

You're adding elements to an already filled array. Array indexes start from 0, When you declared :
public static String[] specialConsonants = new String[4];
That means you can only use specialConsonants[0] to specialConsonants[3]
I suggest you use a hashmap for this thing.
HashMap<String, String> specialConsonants = new HashMap<String, String>();
....
specialConsonants.put("ං" , "ng" );
....

You've declared specialConsonants as an array of length 4, but you're assigning 6 elements to it.
specialConsonants[4] has enough room for elements 0, 1, 2, and 3.
You need to declare it as specialConsonants[6] if you want indices 0 - 5.
Then you need to call setSpecial() before you use the array in your loop.

the array definition looks wrong, seems you want two same size array but you defined as :
public static String[] specialConsonants = new String[4];
public static String[] specialConsonantsUni = new String[6];
I think it should be:
public static String[] specialConsonants = new String[6];
public static String[] specialConsonantsUni = new String[6];

Related

ArrayList<String[]> won't add more than one item

I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData;
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData = new ArrayList<String[]>();
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!
you clear out foodData every time you call createFood remove this line:
foodData = new ArrayList();
and move the initialization to a static level , like this:
static JComboBox<String> foodChoice;
DefaultTableModel foodList;
static String[] newFood;
static List<String[]> foodData = new ArrayList<String[]>();
JTextField newFoodText, portionText, carbsText;
public Main() {
void createFood() {
String[] foodProperties = new String[3];
foodProperties[0] = newFoodText.getText();
foodProperties[1] = portionText.getText();
foodProperties[2] = carbsText.getText();
Main.createFood(foodProperties);
}
static void createFood(String[] foodArray) {
foodData.add(foodArray);
foodChoice.addItem(foodArray[0]);
}
void addFoodToTable() {
String[] s = new String[3];
s = (String[]) foodData.get(foodChoice.getSelectedIndex());
System.out.println(foodData.get(0));
System.out.println(foodData.get(1));
}
Every time you call createFood(String[] foodArray) you create a new List instead of just adding the incoming item to the existing list.
Create the ArrayList in a different place and remove the line from the createFood method and it should work fine.
Worked like a charm. Man I don't know how I missed that... I guess when you look at the same problem for too long you miss the obvious. Thanks guys!

Java, getter for array values (array dynamically defined)

I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}

Passing a string array as a parameter to a function java

I would like to pass a string array as a parameter to a function. Please look at the code below
String[] stringArray = {'a', 'b', 'c', 'd', 'e'};
functionFoo(stringArray);
Instead of:
functionFoo('a', 'b', 'c', 'd', 'e');
but if I do this I am getting an error stating that convert String[] into String. I would like to know if it is possible to pass the values like that or what is the correct way to do it.
How about:
public class test {
public static void someFunction(String[] strArray) {
// do something
}
public static void main(String[] args) {
String[] strArray = new String[]{"Foo","Bar","Baz"};
someFunction(strArray);
}
}
All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.
There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-
String concat (String ... strings)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < strings.length; i++)
sb.append (strings [i]);
return sb.toString ();
}
Here we can call the function like concat(a,b,c,d) or any number of params you want.
More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html
I believe this should be the way this is done...
public static void function(String [] array){
...
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
look at familiar main method which takes string array as param
More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}
Feel free to use this how ever you like.
/*
* The extendStrArray() method will takes a number "n" and
* a String Array "strArray" and will return a new array
* containing 'n' new positions. This new returned array
* can then be assigned to a new array, or the existing
* one to "extend" it, it contain the old value in the
* new array with the addition n empty positions.
*/
private String[] extendStrArray(int n, String[] strArray){
String[] old_str_array = strArray;
String[] new_str_array = new String[(old_str_array.length + n)];
for(int i = 0; i < old_str_array.length; i++ ){
new_str_array[i] = old_str_array[i];
}//end for loop
return new_str_array;
}//end extendStrArray()
Basically I would use it like this:
String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.
I think you forget to register the parameter as String[]
please check the below code for more details
package FirstTestNgPackage;
import java.util.ArrayList;
import java.util.Arrays;
public class testingclass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("Hello");
int size = 7;
String myArray[] = new String[size];
System.out.println("Enter elements of the array (Strings) :: ");
for(int i=0; i<size; i++)
{
myArray[i] = "testing"+i;
}
System.out.println(Arrays.toString(myArray));
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
System.out.println("Enter the element that is to be added:");
myArray = myList.toArray(myArray);
someFunction(myArray);
}
public static void someFunction(String[] strArray)
{
System.out.println("in function");
System.out.println("in function length"+strArray.length );
System.out.println(Arrays.toString(strArray));
}
}
just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...
Thank you

transfer arraylist to double array[0] in java

i have this code:
public class Test{
arrayList<String> list = new ArrayList<String>();
String[][] temp_list;
public static void main(String[] args)
{
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
i want to transfer the first item in 'list' into temp_list[0].compiling is success but i got error when i run it.this is the error:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:this line=>temp_list[0] = temp.split(" ");)
anyone can help me?
This is because you haven't allocated any 2D-array for temp_list. (Which array should the result of split be stored in?)
Here's a working version of your snippet.
import java.util.ArrayList;
public class Test {
static ArrayList<String> list = new ArrayList<String>();
static String[][] temp_list;
public static void main(String[] args) {
list.add("hello wold");
// allocate memory for 10 string-arrays.
temp_list = new String[10][]; <-----------
String temp = list.get(0);
temp_list[0] = temp.split(" ");
}
}
This code would will not compile since list is declared as a member variable of the class but main is a static method.
As written, list has nothing added too so the call to list.get(0) will throw an Exception (not null pointer though).
The array temp_list is not allocated (no new) in the code given so trying assign into it will throw a null pointer exception.
You need to initialize temp_list before you use it. You need to specify the size of the array. For example:
int sizeOfArray = 5;
String[][] temp_list = new String[sizeOfArray][];

Java: how to initialize String[]?

Error
% javac StringTest.java
StringTest.java:4: variable errorSoon might not have been initialized
errorSoon[0] = "Error, why?";
Code
public class StringTest {
public static void main(String[] args) {
String[] errorSoon;
errorSoon[0] = "Error, why?";
}
}
You need to initialize errorSoon, as indicated by the error message, you have only declared it.
String[] errorSoon; // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement
You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.
If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.
As a side note, you could also initialize the String array inside braces, { } as so,
String[] errorSoon = {"Hello", "World"};
which is equivalent to
String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
In Java 8 we can also make use of streams e.g.
String[] strings = Stream.of("First", "Second", "Third").toArray(String[]::new);
In case we already have a list of strings (stringList) then we can collect into string array as:
String[] strings = stringList.stream().toArray(String[]::new);
I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).
public class StringTest {
public static void main(String[] args) {
String[] errorSoon = new String[100];
errorSoon[0] = "Error, why?";
//another approach would be direct initialization
String[] errorsoon = {"Error , why?"};
}
}
String[] arr = {"foo", "bar"};
If you pass a string array to a method, do:
myFunc(arr);
or do:
myFunc(new String[] {"foo", "bar"});
String[] errorSoon = new String[n];
With n being how many strings it needs to hold.
You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
You can use below code to initialize size and set empty value to array of Strings
String[] row = new String[size];
Arrays.fill(row, "");
String Declaration:
String str;
String Initialization
String[] str=new String[3];//if we give string[2] will get Exception insted
str[0]="Tej";
str[1]="Good";
str[2]="Girl";
String str="SSN";
We can get individual character in String:
char chr=str.charAt(0);`//output will be S`
If I want to to get individual character Ascii value like this:
System.out.println((int)chr); //output:83
Now i want to convert Ascii value into Charecter/Symbol.
int n=(int)chr;
System.out.println((char)n);//output:S
String[] string=new String[60];
System.out.println(string.length);
it is initialization and getting the STRING LENGTH code in very simple way for beginners

Categories

Resources