adding elements from list to string array - java

I have a String array like,
String[] abc= new String[]{};
and my List has some values. I iterate the list and add each list element to string array.
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}
errList.size() has 6 values. But when the for loops executed I get java.lang.ArrayIndexOutOfBoundsException. Any inputs?

You're creating a String[] object of zero length; so, when you try to assign an item to abc[i], it is accessing an index not within your bounds 0 <= i < 0.
You should allocate abc with a length instead:
String[] abc= new String[errList.size()];
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}

You need to craete the string array with the same size as the list. It is not dynamic. Perhaps you can tell what you are trying to achieve with this exercise.

Did you try to use for each loop which is widely used in collection framework?

String[] abc = errList.toArray(new String[0]);
Or:
String[] abc = new String[errList.size()];
errList.toArray(abc);

I would just do this
String[] abc= errList.toArray(new String[errList.size()]);

Related

How to call multiple variable of string with numbering in loop?

What i am trying to achieve is, let's say I've these variables below:
String num1 = "blah1";
String num2 = "blah2";
String num3 = "blah3";
String num4 = "blah4";
String num5 = "blah5";
Now i want to create a single string variable which would iterate the all values of string's variable inside loop.
for(int i=0; i<=5; i++){
System.out.println(num+""+i); //I know, this would give me some errors. But i want to make something like this to call all string variables.
}
Here i want to print all the values of string's variable by using loop, How to achieve this?
Help would be appreciated!
This is a use case for an array:
String nums[] = new String[] {
"blah1",
"blah2",
"blah3",
"blah4",
"blah5"
}
And then you can easily iterate through the values (note that you don't need to duplicate the number of elements (5) ):
for(int i=0; i<nums.length; i++) {
System.out.println(nums[i]);
}
More about arrays in the Oracle tutorial.
Alternatively, you may use a List instead of an array.
What you need is an Array - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
An Array is a container containing a fixed number of values that are the same type, eg:
String [] nums = new String[5];
The above line creates a array called nums of type String which can hold 5 individual String values (they are initially null).
Another way to declare this would be to use:
String [] alt_nums = {"blah1","blah2","blah3","blah4","blah5"};
This set's each value stored in alt_nums to a specific value as declared in the curly braces.
To iterate through an Array you can use an iterative for loop
for(int i = 0; i < alt_nums.length; i++) {
System.out.println(alt_nums[i]);
}
or you can use an enhanced for loop which does this automatically.
for(String num : alt_nums) {
System.out.println(num);
}
You can also use java 8:
List<String> strings = Arrays.asList("sad", "asdf");
strings.forEach(str -> System.out.println(str));

How can I get textbox value into array and convert into integer in java

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
}

How to get index of value in array?

I have an array like this :
String[] array = { "Designation1", "Designation2", "Designation3" };
If user put "Designation2" as input then the code should return 1.
It may be very simple question, but I am very new in Java. So please give some suggestions.
Consider using List instead of array (of just wrap your array in List). This way you will have access to method like indexOf(element) which will return index of first founded element, of -1 if no element in array was found.
String[] array = { "Designation1", "Designation2", "Designation3" };
List<String> list = Arrays.asList(array);
System.out.println(list.indexOf("Designation2")); //prints 1
System.out.println(list.indexOf("foo")); //prints -1
You can loop over the Strings in the array and find the index for which the String matches what you are looking for.
int index = -1;
for (int i=0; i<array.length;i++) {
if (array[i].equals(value)) {
index = i;
break;
}
}
You could just use a for loop
String[] array = { "Designation1", "Designation2", "Designation3" };
Scanner kb=new Scanner(System.in);
String input=kb.next();
int index;
for(int i=0;i<array.length;i++)
{
if(array[i].equalsIgnoreCase(input))
index=i;
}
You can do it like this.
String userinput="Designation2";
String[] array = { "Designation1", "Designation2", "Designation3" };
int length=array.length();
int index=0;
for(int i=0;i<length;i++)
{
if(array[i].equals(userinput))
{
index=i;
break;
}
}
And index will give you the array key that user wants.
Regards..
There are no direct search method for array so you need to convert it to list first
String[] array = { "Designation1", "Designation2", "Designation3" };
assert Arrays.asList(array).indexOf("Designation2") == 1;
assert Arrays.asList(array).indexOf("Anything else") == -1;
Do not forget that -1 mean 'not found'
Or you can sort it and use binarySearch
You can use ArrayUtils from Apache Commons.
String[] array = { "Designation1", "Designation2", "Designation3" };
System.out.println(ArrayUtils.indexOf(array, "Designation1"));//0
System.out.println(ArrayUtils.indexOf(array, "Designation2"));//1
System.out.println(ArrayUtils.indexOf(array, "Designation3"));//2
In order to do this task, you can use two arrays, one for key names and ones for their values. Simply search for the key in the first array, get the index of the key name and use it to get the value from the second array. It's not the most efficient, and this is probably not the best answer, but it works for me.
Just make sure the indexes in the arrays line up, for example:
{"my","three","keys"};
{"My","Three","Values"};
In this case, the key/value setup would be;
my/My
three/Three
keys/Values
In your case, you don't need to use the value array, just use the index.
Also try using ArrayList instead of arrays, as you can use ArrayList.indexOf(key) to get the index of key in the ArrayList.
Hope this helps you and others with this problem. ☺

Use linked list or array to reverse a string in Java?

I believe that we can use a for loop to reverse a string in Java. Just like below:
String[] name = new String[10];
for(int i = name.length; i >0; i--){
System.out.print(name[i-1]);
}
But another implementation is using LinkedList. So my understanding is to use LinkedList when the client is not sure how long the string array might increase dynamically. Is that correct?
A linked list of characters can be used to do this.
In this instance, think of an array list as an array with unlimited length. For this, instead of adding values to the END of the array, we will add them to the BEGINNING of the linked list
LinkedList<Character> linkedList = new LinkedList<Character>();
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
linkedList.addFirst(str.charAt(i));
}
//whenever it is time to print the value....
for (char c : linkedList) {
//Print it out, one character at a time
System.out.print(c);
}
Whenever you have to add more characters to it, just use linkedList.addFirst() to append it to the beginning.

Java String formation for ListView

I have created a Java code for my Android App.
String[] MovieName=new String[]{};
for (int i = 0; i < 15; i++)
{
MovieName[i]=movieAtt.getAttributeValue( "name" ); //Value coming from my XML
}
ListViewObject.setAdapter(new ArrayAdapter<String>(screen2.this,android.R.layout.simple_list_item_1 , MovieName));
This code throws an Exception.
I think i am not inserting vaues properly inside Java String Array.
All i want is to have a variable like MovieName={"1","2", "3"} to feed into the ListView of my code.
This is not much helpful too :
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
You initialize an empty array.
Try this
String[] MovieName = new String[15];
Your initilizing an empty string array. That will give you an ArrayOutOfBoundException.
If you always have 15 entries you could initialize it to 15.
String[] MovieName=new String[15];
Otherwise you could create an ArrayList and convert it to an array after you filled it.
If number of elements in MovieName is constant, then you should initialise it as
String[] MovieName=new String[15];
Your current initialisation is equal to
String[] MovieName=new String[0];

Categories

Resources