Assign value from one character array into another in java - java

I am writing program to eliminate vowels in a String. What I want to do is check if the value of the character in the string is a Vowel. If it is false I want to store it in another array as follows:
if(isVowel(char_str[i]) == false) {
temp[index] = char_str[i];
index = index + 1;
}
I get an array out of Bounds exception for the 2nd line. I have initialised both the arrays as follows:
String str="Education";
char char_str[]=str.toCharArray();
char temp[] = {};
Can someone explain exactly what I am doing that is causing the error. I am a bit out of touch with the working of arrays in Java.

You cannot add an element to an array like this without specifying the array length. You can use ArrayList instead to add new elements without specifying the length. So either initialize the array length like this -
char temp[] = new char[100]; // Assuming 100 is the highest length
or declare an ArrayList like this -
List<Character> temp = new ArrayList<Character>();
You can add a new element to an ArrayList by using the add method.
temp.add(char_str[i]);

You are attempting to access an element of an empty array.
This line
char temp[] = {};
Creates an empty array - one with no elements.
So this
temp[index] = ...
Will explode because there are no positions to assign a value to.
Allocate some space, eg:
char temp[] = new char[str.length()];

Related

Split a field through array in java

I would like to know how to split a field through array using Java. For example we have GLaccount like AAAA-BBBB-CCCC and we would like to split each component and store it in an variable however the GLaccount may have AAAA-BBBB (no third component) so in this case variable segment3 throws NULL POINTER exception so I am not sure on how to fix this since I am new to Java.
String GL = getOwner().getGL("GLACCT");
String segment1 = GL.split("-")[0];
String segment2 = GL.split("-")[1];
String segment3 = GL.split("-")[2];
Using split("-" ) will give you an array of strings.
before using array value, you can check the size of array that if it contains enough elements to use..
String GL = getOwner().getGL("GLACCT");
String[] array=GL.split("-");
String segment1 = array[0];
String segment2 = array[1];
//check if array have 3rd element
if(array.length >2)
String segment3 = array[2];
else
System.out.println("No third element") ;
Use split method (once) and check returned array length :
String[] values3 = "AAAA-BBBB-CCCC".split("-");
// values.length == 3
String[] values2 = "AAAA-BBBB".split("-");
// values2.length == 2
import java.util.Arrays;
List<String> list = Arrays.asList(GL.split("-"));
With this code you do not need to think if you have 2,3 or 10 strings, and to add new if for every new one.

String and array mixing syntax and a very rare usage

I have found very interesting but yet very strange String and array mixing up(syntax). See below code:
Example A:
int x = (int)(Math.random()*4 );
String n = new String[] {"FF", "RR"}[x];
System.out.println(n) ;
It outputs "FF" or "RR" when the random number is 0 or 1. My question is how that can happen. I am unable to understand the syntax used in Example A. I have used a very normal String array syntax just as below :
String s[] ;
s = new String[]{"dd", "rr"};
Or
String s [] = {"gg", "ss"};
But I haven't seen the top syntax (Example A). Can someone pitch in to help me understand how the top syntax is treated and executed. Advance thanks.
String n = new String[] {"FF", "RR"}[x];
^^^^^^^^^^^^^^^^^^^^^^^^^
This creates an anonymous array containing two elements, "FF" and "RR". An anonymous array is a temporary object that has no name and is destroyed as soon as the statement is finished executing. That anonymous array is then indexed using the [] operator.
String n = new String[] {"FF", "RR"}[x];
^^^
This returns the x'th element of the anonymous array.
Note that there appears to be a bug in this program; if the random number causes x to be greater than 1, you'll get an ArrayIndexOutOfBoundsException.
new String[] {"FF", "RR"} is an expression of type "array of String". This is why you can assign it to s in
String[] s = new String[] {"FF", "RR"};
Since it's of type "array of Strings", you can use the [] operator on it to get the String at a given index. And you must put an int inside the brackets. And xis an int.
So new String[] {"FF", "RR"}[x] is the element at index x of the array new String[] {"FF", "RR"}. This element is of type String. So you can assign it to the variable n, which is also declared as a String.
That's basically the same thing as doing
char c = "hello".charAt(2);
or
int i = new Person().getName().substring(2).indexOf('o');
It is bascially the same as your second notation.
The second line is equivalent to
String s[]= new String[]{"FF","RR"};
String n = s[x];
It's just that s is anonymous in this instance.
This of it like this: When you are normally access an element in a String array, what do you do?
String s = arr[0];
That gets the first element in the array. Now you are doing this:
String n = new String[] {"FF", "RR"}[x];
You are simply getting an element from the array immediately upon creation. Or, the xth element. Note that you program will fail if the random number is outside the bounds of the array.

Is it possible to contruct array in Java without number of elements?

I have some problem when using array in Java. If I declare an array of character like this, my program will throw exception "out of bound array":
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
I do not know why it is ok when i replace the first line by:
char[] ipx = new char[64];
I think both of them are correct because i used to delare new string like this:
String newString = "";
what's the difference between those ?
Many thanks for any help you may be able to provide
I do not know why it is ok when i replace the first line by:
Because char[] ipx = {}; is equivalent to char[] ipx = new char[0]; // zero sized array;
and in latter case char[] ipx = new char[64]; you allocate 64 chars for your array.
No, it has to be initialized to a size at some point. In your example, you can just use: myString.toCharArray();
Typically you'd use Lists for things of unknown size and then do myList.toArray();
In a nutshell, you should not attempt to draw any parallels between String and char[]. They are very different creatures in Java.
If you wish to access element k of an array, you need to ensure that k is a valid index (i.e. that the array is large enough). A zero-length array ({}) is not large enough for any element access.
Is it possible to contruct array in Java without number of elements?
In your case, yes, just replace
char[] ipx = {};
for( int i =0; i <= 63 ; i++ ){
ipx[i] = myString.charAt(i);
}
by
char[] ipx = myString.toCharArray();
You can also use a ArrayList<Character> without declaring the number of elements.
Yes, all arrays in java are basic data structures and must have a pre-defined fixed length. Changing the length necessarily requires creating a new array.
If you want to handle collections of objects with variable size, what you want is a Collections Object from the Java libraries, which is more intelligent than a basic data array.
The List class in particular, ArrayList, will perform exactly what you want. It is a List of objects (instead of an array) and will resize itself naturally as you add or remove elements.
If you do char[] ipx = {}, it means you create a reference ipx. Same as you do char* ipx in C++, which is a pointer points to a random address. In order to store elements in it, you need to allocate memory like in C++ you need to do char* ipx = new char[64]. Therefore, if you only do char[]ipx = {} which is equivalent to char[]ipx = new char[0] in Java.

How do you determine size of string array java?

How do i read a file and determine the # of array elements without having to look at the text file itself?
String temp = fileScan.toString();
String[] tokens = temp.split("[\n]+");
// numArrayElements = ?
Use the length property of the array:
int numArrayElements = tokens.length;
The proper expression is tokens.length. So, you can assign numArrayElements like this:
int numArrayElements = tokens.length;
This counts the number of elements in the tokens array. You can count the number of elements in any array in the same way.

how do I ignore/delete values of an array in java

I have a list of words , there are 4 words, it cant contain more that 4 its just an example. I want to use just 2 of the words the rest of them should be ignored or deleted e.g :
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
int numberOfPlanets = planetsArray.length;
the result i get is 4. How do i delete the rest of the words if my list contains more that 2 words ?
As suggested in your previous question, you can use
String[] fewPlanets = new String[]{planets[0], planets[1]};
Just make sure the planets array has 2 elements or more to avoid an ArrayIndexOutOfBoundsException. You can use length to check it: if (planets.length >= 2)
For a more sophisticated solution, you could also do this using System.arrayCopy() if you're using Java 1.5 or earlier,
int numberOfElements = 2;
String[] fewPlanets = new String[2];
System.arraycopy(planets, 0, fewPlanets, 0, numberOfElements);
or Arrays.copyOf() if you're using Java 1.6 or later:
int numberOfElements = 2;
String[] fewPlanets = Arrays.copyOf(planets, numberOfElements);
String planets = "Moon,Sun,Jupiter,Mars";
String[] planetsArray = planets.split(",");
if(planetsArray .length > 2){
String []newArr = new String[2];
newArr[0]=planetsArray [0];
newArr[1]=planetsArray [2];
planetsArray = newArr ;
}
Use Arrays.asList to get a List of Strings from String[] planetsArray.
Then use the methods of the List interface -contains,remove,add, ...- to simply do whatever you want on that List.
If you need to select the first 2 planets just copy the array:
String[] newPlanetsArray = Arrays.CopyOf(planetsArray, 2);
If you need to select 2 specific planets you can apply the following algorithm:
First, create a new array with 2 elements. Then, iterate through the elements in the original array and if the current element is a match add it to the new array (keep track of the current position in the new array to add the next element).
String[] newPlanetsArray = new String[2];
for(int i = 0, int j = 0; i < planetsArray.length; i++) {
if (planetsArray[i].equals("Jupiter") || planetsArray[i].equals("Mars")) {
newPlanetsArray[j++] = planetsArray[i];
if (j > 1)
break;
}
}
You could use an idea from How to find nth occurrence of character in a string? and avoid reading the remaining values from your comma separated string input. Simply locate the second comma and substring upto there
(Of course if your code snippet is just an example and you do not have a comma separated input, then please ignore this suggestion :)

Categories