I getting ArrayIndexOutOfBoundsException - arrays

I am trying to convert a String array to int array and then compare elements if they are equal so far i am getting an error, first this is the method that converts string array to to int array
private static int[] convertStringArrayToIntArray(String[] strVals) {
int[] intVals = new int[strVals.length];
for (int i=0; i < strVals.length; i++) {
intVals[i] = Integer.parseInt(strVals[i]);
}
Arrays.sort(intVals);
return intVals;
}
Now the method below is where i am getting the exception
public static String ScaleBalancingCorrect(String[] strArr) {
int[] startWeights = convertStringArrayToIntArray(strArr[0].replaceAll("[^0-9,]", "").split(","));
int[] availWeights = convertStringArrayToIntArray(("0," + strArr[1]).replaceAll("[^0-9,]", "").split(","));
if (startWeights[0] != startWeights[1]) { //I get exception here
for (int i = 0; i < availWeights.length; i++) {
// omited code for brevity
this is what i was running when i got the exception
public static void main(String [] arg) {
String [] arr = {"34","1277"};
ScaleBalancingCorrect(arr);
}

Maybe it's just a typo and you wanted to write if (startWeights[0] != availWeights[1]).
availWeights will always have at least two elements, since you add 0 as a first element before the supplied other element(s).
startWeights, however, as in your example, may only have one element (in your example, it's 34).

Related

Problem accessing multidimensional array length and fields

Here is code to test a multidimensional array
public class Multiarraytest {
public int size_main = 5;
public int size_aux = 20;
Multiarraytest() {
float[][] float_mul = new float[size_main][size_aux];
}
void init_int(Multiarraytest mul) {
int i, j = 0;
while(i < mul.length) {
while(j < mul[i].length) {
mul[i][j] = (i + (j/10));
j++;
}
i++;
}
}
public static void main(String[] args) {
}
}
But
here are the results of javac Multiarraytest.java.
error: cannot find symbol While(i < mul.length)
^
symbol: variable length
location: variable mul of type Multiarraytest
error: array required, but Multiarraytest found while(j < mul[i].length
^
error: array required, but Multiarraytest found mul[i][j] = (i + (j/10));
I have not found what's going wrong.
mul is a 2 dimensional array
mul.length should give the length of the first array
mul[1] should lead to the array nested in the first case of mul
mul[1].length should give the length of the array nested in the first case of mul
mul[1][2] should give access to read/write of the second case of the array nested in the first case of mul.
Where have I made a mistake?
This is a cut down version of what I was doing but same errors are reported. I read tutorial and close copy-cut it. Except it's a float multidimensional array instead of int multidimensional array and I try to fill it in a loop instead at the initializing time.

Java method returning blank array

I'm new to java and having trouble basically passing an array through to a method in another class, using the values to compute a new array, and then passing that back again to print. The problem is that when it prints the array it always prints the empty string. When I step through in debug mode I can see that the values are getting passed in and the array gets generated, but then when it prints it is always empty. It seems like somehow to code is failing to return the correct array maybe. Here is my code
public static void main(String[] args) {
double[] rnoDivs;
double[] rnoEarnings;
Company rno = new Company();
rnoDivs = new double[] {355, 355, 315, 240, 190};
rno.yearlyDividendsGrowth(rnoDivs);
rnoEarnings = new double[] {0.019, 3.451, 5.210, 3.543, 2.960};
rno.yearlyEarningsGrowth(rnoEarnings);
This is passed through to my other class
public class Company {
double[] yearlyEarningsGrowth = {};
public double[] getYearlyEarningsGrowth(){return yearlyEarningsGrowth;}
public double[] yearlyEarningsGrowth(double[] yearlyEarnings){
double[] yearlyEarningsGrowth = new double[yearlyEarnings.length];
for (int x = 0; x <= yearlyEarnings.length; x++) {
if (x < yearlyEarnings.length - 1) {
yearlyEarningsGrowth[x] = (yearlyEarnings[x] / yearlyEarnings[x + 1]) * 100;
}
}
return yearlyEarningsGrowth;
}
}
And then I try to print this statment
Company[] companies = {rno};
for(int i=0; i < companies.length; i++) {
double[] array = companies[i].getYearlyEarningsGrowth();
System.out.println("Yearly earnings growth: " + Arrays.toString(array));
}
But then I just get the array "[]". Any help with this would be appreciated! I seem to be going in circles because everything looks correct.

Given an array in which arr[i] = i-1 with the following method, what will be the output?

I'm given the following method written in pseudo-code
for i=1 to floor(n/2)
if arr[i] != 0 then
for(j=2 to floor(n/i)
arr[i*j] = 0
I need to find the output and to prove that it's indeed the output.
So far I tried to write the code in Java and to try different inputs and array sizes but to no avail.
Putting it here if it's of any help:
public class Checking
{
private static int method(int[] A,int n)
{
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
if(A[i] != 0)
{
for(int j=2;j<=java.lang.Math.floor(n/i);j++)
{
A[i*j]=0;
System.out.println("The index ofA["+i*j+"] became "+A[i*j]);
}
}
//System.out.print(", "+A[i]);
}
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
return 0;
}
public static void main(String[] args)
{
int[] A = {-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
System.out.println(method(A,20));
}
}
Thank you.
You can change the following:
In your main method remove
System.out.println(method(A,20));
as it will always print 0 as you return 0; from the method().
As you print everything in your method() change the following (as it does not print the full array but from index 1 (missing index 0) to floor n/2)
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
to
for (int i=0;i<A.length; i++)
{
System.out.print(", "+A[i]);
}
So you can print the whole array.
For simplicity you can use Array's print method to print the array without a for loop
System.out.println(Arrays.toString(A));

String to Character Array

I have a problem with my code below:
public class stringToChar {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
char[] sCharArr;
String[] odd = new String[n];
String[] even = new String[n];
for(int i = 0; i < n; i++) {
sCharArr = in.next().toCharArray();
for(int j = 0; j < sCharArr.length; j++) {
if(j % 2 == 0)
even[i] += sCharArr[j];
else
odd[i] += sCharArr[j];
}
}
for(int i = 0; i < n; i++) {
System.out.println(even[i] + " " + odd[i]);
}
}
}
My issue is on the output it has a Null in the result. Here is a sample scenario:
2
John
Cena
Answer should be:
Jh on
Cn ea
But my code answer is:
NullJh Nullon
NullCn Nullea
Your problem is that the new arrays are initialized with all null Strings. Then your code is not assigning values to all array elements, but just to some of them!
Finally you print your array, and surprise, those values that were null and that have not been changed - are still null (and when you print a null string ... it prints "null" [ yes, null, not Null; you got a little mistake there in your output example ]
You see, you iterate from 0 to the length of your two arrays. And if the number is even, you put a value in the even[i]; and if the value is odd, it goes to odd[i]. Lets take even - in that case, odd[i] simply stays null!
One way to fix that:
List<String> even = new ArrayList<>();
List<String> odd = new ArrayList<>();
And now, instead of setting a certain index in even/odd; you simply do:
even.add(some new value);
and to add those single characters:
even.add(new String(sCharArr));
Doing so, even and odd will (in the end) contain exactly the values that you added to each list; but no "residual" nulls. For the record: the way how you split up strings, to then pull them back into a String array isn't exactly the most simple/straight forward way to solve the problem.
But I leave "further" simplifications" as exercise to the user.

sorting strings in an array alphabetically

I came up with this code to try and sort out an array of strings (I don't want to use ints or imports as I'm trying to understand iteration loops), but it only rearranges the first two strings. Can anyone point out my mistakes?
public class Alpha8 {
public static void main(String[] args) {
String[] Names = {"O","B","K","S","D","M","N","A"};
String temp = null;
for(int i=0;i<Names.length;i++){
for(int j = i+1;j<Names.length;j++) {
if(Names[j].compareTo(Names[i])<0)
temp = Names[i];
Names[i] = Names[j];
Names[j] = temp;
for( i = 0;i<Names.length;i++){
System.out.println(Names[i]);
}
}
}
}
}
You have made two mistakes:
You are printing the array inside your 'swap' code. You should only print the array once the sorting is complete.
You only iterate through the array once. For a bubble sort (which is what you are implementing) you need to keep iterating through until no swaps occur.
The method should look something like:
boolean hasSwapped;
do {
hasSwapped = false;
for (int i = 1; i < names.size(); i++) {
if (names[i-1].compareTo(names[i]) > 0) {
swap(names[i-1], names[i]);
hasSwapped = true;
}
}
} while (hasSwapped);

Resources