Adding elements dynamically in String array but index 0 showing null? - java

I want to add some values in string array dynamically by using for loop.
when i debug the code at first for loop it is showing values which are adding.I want to check if any one of the string equals to my given value.but in for loop 2 at index 0 it showing null and at index 1 it showing the string value.
for(int i=0;i<someval;i++) {
String[] mylist = new String[someval];
mylist[i]=previousVal;
System.out.println("Previous Value : " +mylist[i]);
}
for (int j = 0; j <=mylist.length; j++) {
if (mylist[j].equals(givenValue) ) { {
System.out.println("your value found in the array");
}
}

The problem is that you are creating a new array using
mylist = new String...
during each loop iteration.
So, it doesn't really matter if you write something to an array, if the next step consists of throwing that array away.
In other words: make sure that you create the array just once; preferable before entering your loop.

Related

Throwing an IndexOutOfBoundsException and I don't understand how

the code in this class is throwing an "indexOutOfBounds exception". I don't understand why its throwing that, I'm just trying to loop through each row, and each column, then assign each column to a variable. For more clarification, initializeArray is a regular 2D ARRAY, and initializedArray is an ARRAYLIST.
//Array to initialize course list (format is first name, last name, student number}
//This is the array that I will be using to store each row into the ArrayList
String [] [] initializeArray =
{{"Hasan","Ahmed","462948"},
{"Abdul","Alvi","764226"},
{"Omar","Askalany","719049"},
{"Harsim","Grewal","438629"},
{"Anis","Habib","576510"},
{"Hamiz","Hasan","621802"},
{"Bilal","Hussain","417440"},
{"Mazhar","Jabakhan","603544"},
{"Tharsh","Kamalan","447615"},
{"Rohan","Kanjani","443604"}};
//Setting up an ordered collection class of Students using the values in initializeArray
//The parameter "Student", is a class. Student(String firstName, String lastName, String stuNum)
ArrayList<Student> initializedArray = new ArrayList<Student>();
//for every row in initializeArray
for(int row = 0; row<initializeArray.length; row++)
{
//for every column in initializeArray
for(int col = 0; col<initializeArray[row].length; col++)
{
String temp = initializeArray[row][col]; //set the first element to temp
String temp2 = initializeArray[row][col+1]; //set the second element to temp2
String temp3 = initializeArray[row][col+2]; //set the third element to temp3, this is where the run-time error is happening, but its happening with the other temp vars as well
initializedArray.add(new Student(temp, temp2, temp3));
}
}
System.out.println(initializedArray);
The problem is that your index is out of bounds just like the exception says.
Have a look at initializeArray[row][col+1]; and the loop condition col<initializeArray[row].length. What happens when col has the value initializeArray[row].length - 1 and you add 1? The index is outside the allowed range [0, initializeArray[row].length-1].
In your case you know that there are only 3 columns, so you probably just mean initializeArray[row][0], initializeArray[row][1] etc.
In other cases you actually might need to loop over an array and you might want to addess indices after the "current" one (e.g. array[i+1]) but in thos cases you need to make sure that the loop condition takes that into account or that you check inside the loop.
Assume you want to do some calculation based on the elements at i as well as i-1 and i+1 in one iteration. In that case your loop should be:
for(int i = 1;i < array.length - 1; i++)
That way you make sure that i-1 is never < 0 and i+1 is never >= array.length.
Update
As per the question in the comment, here's how you could iterate over the array to print (and for education purposes I'll use a foreach loop) - please note that this is an exception, don't add other questions here but post a new one to keep things simple:
for(Student student : initializedArray) {
System.out.println(student.getGivenName() + " " + student.getFamiliyName() + " " + student.getNumber());
}
Of course this assumes your Student class has those methods.
To make your life easier, override toString():
class Student {
... //other code
#Override
public String toString() {
return givenName + " " + familyName + " " + number;
}
}
Then when printing the list you should get something like "Hasan Ahmed 462948, Abdul Alvi 764226, ...". Using the foreach loop would then look like this:
for(Student student : initializedArray) {
System.out.println(student);
}
all you need to do is to remove the second loop and inside first your code will be like this :
String temp = initializeArray[row][0];
String temp2 = initializeArray[row][1];
String temp3 = initializeArray[row][2];
initializedArray.add(new Student(temp, temp2, temp3));
because when you loop inside initializeArray[row] and when you become to col equal to initializeArray[row].length the +1 and +2 will be out of bounds
I would do one loop with
if (initializeArray[row].length > 2) {
initializedArray.add(new Student(initializeArray[row][0], initializeArray[row][1], initializeArray[row][2]));
}
Otherwise, the condition for the inner loop should be
col < initializeArray[row].length - 2
given that you are accessing initializeArray[row][col + 2].

Arraylist - Using switch statement to add string

I am new to programming and my professor has given an assignment that requires us to:
"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
I've done some research to understand some factors of an ArrayList;
to start off, I did this:
import java.util.ArrayList;
public class izeOfArrayList {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
int totalElements = arrayList.size();
System.out.println("ArrayList contains...");
for(int index=0; index < totalElements; index++)
System.out.println(arrayList.get(index));
}
}
This code just gets the number of elements currently stored in my ArrayList, and prints out each element.
I have three questions:
How can I add String values using switch statement?
How can I retrieve the contents of my ArrayList?
How can I check the size of each element in my ArrayList?
"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
Let's decode line by line:
declare on arraylist with the size of 5.
ArrayList<String> myList = new ArrayList<>(5);
Our ArrayList needs to be defined as a list of Strings, so we put those in the angle brackets. The constructor takes a starting size, which is specified as 5.
Use switch statement to add string values to your arraylist.
Completely unintelligible. switch statements are used in flow of control; we can decide to add string values based on some condition, but we cannot generate input with switch statements, and no conditions are specified. This following code is (seemingly) valid for this instruction:
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
Retrieve the contents of your arraylist.
This you have already (mostly) written up:
int totalElements = myList.size();
for(int index = 0; index < totalElements; index++)
String tempElem = myList.get(index); //get access to the individual elem
//here we're going to do something with the current string (probably)
}
Check the size of each element.
I'm assuming that by the 'size of each element', your professor is looking for the length of each String.
int tempElemLength = tempElem.length();
String objects have a length method, it returns an int.
If the element length is less than 8 rerun the program, otherwise count the consonants of each element.
This, while at first glace seems reasonable, is again unintelligible. Here's a possible interpretation of this line:
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
}
Here is a complete response to your assignment as it is currently defined:
import java.util.ArrayList;
public class SizeOfArrayList {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>(5);
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
int totalElements = myList.size();
for (int index = 0; index < totalElements; index++)
String tempElem = myList.get(index);
int tempElemLength = tempElem.length();
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
//guess print them out?
System.out.println('Item ' + index + ': ' + tempElem + ' -> number of consonants: ' + tempElemNumConsonants);
}
}
}
}
This is a solution to your problem as it has been provided; I will bet money that this is not the solution to your homework problem.
In another school of thought, if the focus of the assignment is basic use and understanding of ArrayLists and I was your professor, the assignment that I would have intended to give my students would be as follows:
Declare and ArrayList with the size of 5. Prompt the user for values until they enter 'quit'; use a switch statement to add all String values into the ArrayList that aren't just a number from [0-9]. Loop over each element in the ArrayList; if the length of any String element is less than 8, alert the user then restart the program. If all of the lengths are valid, sum up the consonants of each element. Print out each word and the consonant count, along with a final tally of the number of words along with the total number of consonants.
While I do know that this does not help you with the initial question, I hope it might be able to help you understand what your professor is trying to ask of you.

Only one Occurrence in Java

Scanner in = new Scanner(System.in);
x = new Scanner(new File("C:\\me.txt"));
int count = 0;
ArrayList<String> b = new ArrayList<>();
while((x.hasNext()))
{
String a = x.next();
int num = 0;
for(int i=0;i<count;i++)
{
if((b.get(i).equals(a)))
{num++;}
}
if(num==1)
{b.add(a);}
count++;
}
I want to add the element to b only when the occurence is only one. But there seems some error i keep getting.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Or does b.get(i) equal to NULL in first iteration?
if((b.get(i).equals(a)))
You got this error because b is empty it doesn't contain any element ,and you are trying to access element in it b.get(i) so you got java.lang.IndexOutOfBoundsException, use contains to find if the list have that element and if not add it to the list or use Set it doesn't allow duplicates
int count = 0;
ArrayList<String> b = new ArrayList<>();
while((x.hasNext()))
{
String a = x.next();
if(!b.contains(a)){
b.add(a);
}
count++;
}
Apparently you're trying to use count as the length of b. However, count is incremented more often than b is added to.
Possible solutions are:
Either update count only when you add something to b
or scratch count altogether and use b.size() in the for loop.
Please
check the line
if ((b.get(i).equals(a)));
It contains a semi-colon at the end and I think this is wrong: The next statement in curly braces (num++;) is executed every time and not only if the condition matches.
check if b.get(i) is null before calling equals on it. You know already that a is not null, hence it would make more sense to check for a.equals(b.get(i))
check the usage of count. Its value is not related to the size of the array list, but you use it this way in the loop.In your implementation a situation can arise in which the value of count is greater than the size of the list. This results in an IndexOutOfBoundsException.

java android string and integer functions dont work

Hi I'm not sure if this is a problem with Eclipse or Java but recently my code has stopped working. I only changed things like assigning new variables to store things. My program takes a multi-dimensional string array and should return a new array trimmed of nulls.
public void makebuttons(final int n, String equals) {
//does lots of widget functions and id assignments
String[] items=getArray(Integer.parseInt(data.equnits.substring(n*3, n*3+1)));
unitvalues[n]=Integer.parseInt(data.equnits.substring(n*3, n*3+1));
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items);
//does more code
}
public static String[] getArray(int selection) {
String[] result;//stores the new array
int x=0,j=0 ,ulength = data.units[0].length;//ints used
String temp="";
while(j < ulength && temp!=null) {
temp= data.units[selection][j][0]; //find the actual array length
j++;
}
if(j==ulength)j--;
result = new String[j+1];//initalise array from check
for(x=0; x<=j; x++) { //add data to array
result[x]=data.units[selection][x][0];
}
return result;//return corrected array
}
Integer.parseInt and Integer.valueOf give value of 0 each time for a string like "01,02,03,04" data.equnits stores the string to be converted to integer by checking 2 digits only to select from a large 3 dimensional array. Since its a 3 dimensional array some nulls are present
Null check for the String doesnt seem to work since the while loop doesnt seem to detect it and it ends up being in the array that gets passed into the array adapter for spinner causing NullPointerException while scrolling.
Restarting eclipse doesn't help.
I can't help with your first problem without more information, but this seems to be the issue with your second:
The function substring is inclusive of the first parameter and exclusive of the second. Since you are only adding 1 to the n*3, you only get one character.
Try using:
substring(n*3, n*3+2)
Edit:
Adding the updated code from my comment above:
while(j < ulength && temp != null && !temp.isEmpty())
{
temp = data.units[selection][j];
j++;
}

Finding index of duplicate values in an ArrayList

I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian" exists at index - 0, 4 & 6.
I need to know all these indexes where "Indian" exists and create an arrayList of that.
Here is my code:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.
So if duplicate exists at index - 2,5,7
I get the array size of index as 3.
But the values are {2,2,2,};
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
int i = 0;
before the loop, and at the very end of the loop put
i++;
Then the variable i tells you where you have found the value, so you can add i to the indexes list.

Categories