This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.
Related
I was wondering if this is the most efficient or even good code practice to add arrays to a single array as far as my knowllage goes its time would be O(n). This is only for practice and I want to do it for int [] not for the code to be changed so it is a List.
static int[] allArrayDirections(int row[], int col [], int diag []) {
int counter = 0;
int allDirectionsInMatrix [] = new int [row.length + col.length + diag.length];
for(int i = 0; i < row.length; i++) {
allDirectionsInMatrix[counter++] = row[i];
}
for(int j = 0; j < col.length; j++) {
allDirectionsInMatrix[counter++] = col[j];
}
for(int i = 0; i < diag.length; i++) {
allDirectionsInMatrix[counter++] = diag[i];
}
return allDirectionsInMatrix;
}
You could compare your linear solution to a sort of unravelled:
Find the longest of the three arrays, take its length as counter boundary
assign the longest array to a new variable first, the other two to second and third – just fiddling with the references so the for looks straightforward
loop once from 0 to the counter boundary
fill your target array in three steps, using the other array's length as offset – unless the smaller arrays are already exhausted, so skip them
This will need some add operation for the offset calculation to write to allDirectionsInMatrix and two greater then checks. Depending on the VM's optimization/ array lengths/ call frequency this might cut it in half.
The single for-loop looks similar to this:
// assuming first.length >= second.length >= third.length;
for(int i=0;i<largestLength;i++) {
allDirectionsInMatrix[i]=first[i];
if (second.length > i)
allDirectionsInMatrix[i+first.length]=second[i];
// I assume when called often enough VM does auto trickery
// with the repeated addition of i and first.length
if (third.length > i)
allDirectionsInMatrix[i+first.length+second.length]=third[i];
}
But this might also break other VM optimizations when treating the arrays independently. So really compare runtime. I'd appreciate to read about your measurements.
Just FYI (and not a reals answer to your question, but maybe interesting for comparison)
One way to concatenate integer arrays (using Streams) would be
int[] a = {1,2,3};
int[] b = {4,5,6,7};
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).toArray();
System.out.println(Arrays.toString(c));
(Stream.concat for arrays of other types)
I have to set values in a list of string arrays. How do I write the code to avoid an array out of bound exception.
e.g. this is my code:
for (int i = 0; i < childs.getLength(); i++)
{
String[] slotValues = _newValues.get(i);
if (allSlots) {
NodeList slots = childs.item(i).getChildNodes();
for (int j = 0; j < slotValues.length; j++) {
XmlUtil.setTextContent(slots.item(j), slotValues[j]);
}
} else {
for (int j = 0; j < slotValues.length; j++) {
XmlUtil.setTextContent(XmlUtil.getFeature(_slotNames[j], childs.item(i)), slotValues[j]);
}
}
}
I am a beginner and I do not know how to check if the length of values that I am trying to set in the structure does not give array out of bound exception. i.e. it should be equal to the length of array.
I am a beginner and I do not know how to check if the length of values
that I am trying to set in the structure does not give array out of
bound exception. i.e. it should be equal to the length of array.
Since collections in Java are 0 based, having array arr the first element is arr[0] and the last element will be arr[arr.length-1]. Knowing this you can ensure that your iteration variable (array index) is always >=0 and <array.length.
Having index >= arr.length will result in IndexOutOfBoundsException
Bare in mind, that in your code, you are using single iteration variable to index multiple arrays like here
XmlUtil.getFeature(_slotNames[j], childs.item(i)), slotValues[j])
You are using _slotNames and slotValues with the same index, but you are limiting index with j < slotValues.length so it is dependent on slotValues length. If both arrays are of equal length, that is fine. But if they are not, then you will get mentioned exception if _slotNames will have less elements then slotValues.
This question already has answers here:
How to convert int[] into List<Integer> in Java?
(21 answers)
Closed 5 years ago.
I am trying to find duplicate element in an array. I have already solved it using traversing the array. But now i want to convert array to arraylist and use contains keyword of arraylist.
I am not able to convert array to arraylist and use the contains keyword. please look in following code:
public void findDuplicate2() {
int arr[] = { 1, 2, 3, 4, 5, 3, 7, 5 };
ArrayList<int[]> arrlist = new ArrayList<>(Arrays.asList(arr));
for (i = 0; i < len; i++) {
if (arrlist.contains(arr[i]))
System.out.println(arr[i]);
else
System.out.println("no duplicate" + arr[i]);
}
}
There are a number of problems with your code:
You are creating an ArrayList<int[]>, that is, an array list of arrays of int. This list contains one array, namely the one you started out from. I don’t think this was what you intended. My guess is you wanted an ArrayList<Integer> containing the numbers from the array. khelwood’s link should help you out.
You haven’t declared i nor len. I suggest you use for (int i = 0; i < arr.length; i++).
arrlist.contains(arr[i]) always returns false since a list of arrays cannot contain a number (the numbers inside the array are not searched). It’s a design problem with ArrayList that you can ask for whether it contains an element of the wrong type (there are historical reasons for this). If you change the arraylist to ArrayList<Integer> as I suggested above, it will work, though.
Once you get the above to work, arrlist.contains(arr[i]) will always return true since each number from the array will be in the array list, also the ones that are not duplicates.
Here your arrlist variable is of type int[]. Here your arrlist size is 1(the entire input array as single entry).
So, you can only check the existence of any integer array in the list by using contains method of arrlist. if (arrlist.contains(arr)) //returns true in your case
An easier way to find dublicates is this one:
public void findDuplicate2(){
int arr[] = {1,2,3,4,5,3,7,5};
for (int i = 0; i < arr.length; i++) {
boolean dublicate = false;
for (int j = 0; j < arr.length; j++) {
if(arr[i] == arr[j] && i != j){
System.out.println(arr[i]);
dublicate = true;
break;
}
}
if(!dublicate)
System.out.println("No dublicate " + arr[i]);
}
}
In your code the arraylist contains one element, the array arr. You can check this with
System.out.println(arrlist.get(0));
System.out.println(arrlist.get(1));
The right way would be to transfer each element of arr to arraylist...
This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.
My Selection Sort algorithm is not working.
I am getting the following errors:
//Exception in thread "main" java.lang.NullPointerException
Note: this is for a java class. I do not have a lot of experience. I am done with the assignment. I am trying to understand the reason why my sorting algorithm isn't working.
Any suggestions on how to correct the problem? Tips?
Corrections? ... any help at all will be appreciated.
Here is my code:
private void sortFlowers(String flowerPack[]) {
// TODO: Sort the flowers in the pack (No need to display them here) - Use Selection or Insertion sorts
// NOTE: Special care is needed when dealing with strings! research the compareTo() method with strings
for(int i = 0; i < flowerPack.length; i++){
String currentMinFlow = flowerPack[i];
int minIndex = i;
for(int j = i; j < flowerPack.length; j++){
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){
currentMinFlow = flowerPack[j];
minIndex = j;
}
}
if(minIndex != i){
flowerPack[minIndex] = flowerPack[i];
flowerPack[i] = currentMinFlow;
}
}
}
Exception:
Exception in thread "main" java.lang.NullPointerException at
java.lang.String$CaseInsensitiveComparator.compare(String.java:1181) at
java.lang.String$CaseInsensitiveComparator.compare(String.java:1174) at
java.lang.String.compareToIgnoreCase(String.java:1227) at
Assignment01Driver.sortFlowers(Assignment01Driver.java:112) at
Assignment01Driver.<init>(Assignment01Driver.java:37) at
Assignment01Driver.main(Assignment01Driver.java:5)
The issue is coming from the fact that your array was created with a fixed size.
String[] flowerPack = new String[25];
When you create an array of reference type variables, each variable will be initialized with a value of null. If you call the sortFlowers method before each variable is given a value, you run into an issue.
for(int i = 0; i < flowerPack.length; i++){
String currentMinFlow = flowerPack[i];
In the above segment, you are iterating through all 25 positions in the array, including the values that still have a value of null. Then, the following line causes the error:
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0){
Since you are iterating through the entire array, you end up with values of currentMinFlow that are null. If you try to make a method call on a null reference value, you end up with a NullPointerException.
Generally, you rarely want to use fixed size arrays when you're unsure of how many data items you're likely to have. In this case, you would want to use an ArrayList in place of a standard array. An ArrayList is essentially a dynamic array that grows and shrinks as necessary to contain the elements you store in it. This will get rid of your problem with null values, since this will prevent you from having any unused elements in your array.
Replace
String[] flowerPack = new String[25];
with
ArrayList<String> flowerPack = new ArrayList<>();
If you wanted to add or remove a value from the ArrayList you could do
// Add value.
flowerPack.add(value);
// Remove value
flowerPack.remove(value);
If you want to access a certain element in the ArrayList:
String element = flowerPack.get(indexOfElement);
If you want to get the size of the ArrayList:
int size = flowerPack.size();
And if you don't want to modify your sorting method, you can keep it the same by replacing the line
sortFlowers(flowerPack);
with
sortFlowers(flowerPack.toArray(new String[0]));
For an overview of other ArrayList methods and properties, check the online documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
The error says that you are trying to deal with the array that holds a value of null. to understand better, fill in all 25 spots in the array and run the program, it will not give you any error.
Here is the solution that you need.
private void sortFlowers(String flowerPack[])
{
//get the length of the array by counting arrays where the value is not null.
int length = 0;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
length = length + 1;
}
}
//just confirm that the count is correct.
System.out.println(length);
//set the length to the "length" variable as we have found above.
for(int i = 0; i < length; i++)
{
String currentMinFlow = flowerPack[i];
int minIndex = i;
for(int j = i; j < length;j++){
if(currentMinFlow.compareToIgnoreCase(flowerPack[j]) <0)
{
currentMinFlow = flowerPack[j];
minIndex = j;
}
}
if(minIndex != i){
flowerPack[minIndex] = flowerPack[i];
flowerPack[i] = currentMinFlow;
}
}
}
Just replace your sortFlowers method with above code and check.