If I have a string that contains "Cat" how could I check before hand if anything exists in each individual charAt case. Here is the sample code
for (int i = 0; i < array.length; i++)
{
System.out.println();
for (int j = 0; j < size; j++)
{
System.out.print(array[j].charAt(i) + " ");
}
}
Once i reaches 3 you would get an out of bounds exception. Is there a way that it could print an empty space?
EDIT: Sorry I wasn't clear at all. There are multiple strings that are being printed vertically. So assume the largest string is size of 10 and that the smallest is size of 4. The first four char of each string print fine. But an out of bounds error occurs when the fifth char tries to print since it doesn't exist. Is there any way around that?
You've got i
and j
the wrong way around, that's all.
You should have:
System.out.print(array[i].charAt(j) + " ");
And to make your code more robust, you should rewrite the inner loop to go until it reaches the length of array[i]
, instead of a pre-defined size
variable.
Update: If you want to print the array of strings vertically (so each string is in a column), this is what your code should look like:
for (int i = 0; i < size; i++) // i is the loop variable for the character count, we'll print one line for each character
{
for (int j = 0; j < array.length; j++) // for every string in the array
{
char c = ' '; // print out a space character by default to keep the columns aligned
if ( array[j].length() > i ) // but if the array[j] still has characters left
c = array[j].charAt(i); // print that character instead
System.out.print(c + " "); // here
}
System.out.println(); // and close the line
}
j < size
, then size
should be just array[i].length
- Greg Hewgill 2012-04-03 20:32
how could I check before hand if anything exists in each individual charAt case.
Besides the indexing issue already mentioned by biziclop, you must also check the size of the string before you do a charAt
.
I mean for (int j = 0; j < size; j++)
here size
should be array[j].length()
for this to work.
But why bother with a loop iteration?
You can do just System.out.print(array[i] + " ");