Finding the sum of multiple inputted Arrays - java

I am finding the sum of multiple arrays and have searched various codes and programs but it seems none has worked for me or should I say none has actually made my brain work to create a code based on what I saw. "What I am trying to do is to add the 3 inputed Grade Arrays and then divide it by 3 to get the Array for Average."
package Activity;
import java.util.*;
public class TestCode {
static Scanner sc = new Scanner(System.in);
static int indexMax = 3;
public static void main(String[] args) {
String InfoName[][] = new String[indexMax][2];
Double InfoGrade[][] = new Double[indexMax][3];
InputInfoName(InfoName);
InputGrade(InfoGrade);
PrintInfo(InfoName, ComputeAvg);
}
public static String[][] InputInfoName(String NameArr[][]) {
for (int i = 0; i < indexMax; i++) {
System.out.println();
System.out.println("Enter Student[" + (i + 1) + "]'s Full Name");
System.out.println();
System.out.print("First Name: ");
NameArr[i][0] = sc.nextLine();
System.out.print("Last Name: ");
NameArr[i][1] = sc.nextLine();
}
return NameArr;
}
public static Double[][] InputGrade(Double GradeArr[][]) {
for (int i = 0; i < indexMax; i++) {
System.out.println();
System.out.println("Enter Student[" + (i + 1) + "]'s Grades");
System.out.println();
System.out.print("1st Grade: ");
GradeArr[i][2] = sc.nextDouble();
System.out.print("2nd Grade: ");
GradeArr[i][3] = sc.nextDouble();
System.out.print("3rd Grade: ");
GradeArr[i][4] = sc.nextDouble();
}
return GradeArr;
}
// Main Problem
public static Double[][] ComputeAvg(Double ComputeArr[][]) {
Double AddAvg[][] = new Double[indexMax][];
Double getAvg[][] = new Double[indexMax][];
for (int i = 0; i < indexMax; i++) {
AddAvg[i][] = // I don't know what is next
}
return ComputeArr;
}
// End of Main Problem
public static void PrintInfo(String arr[][], Double ComputeAvg[]) {
System.out.println("");
System.out.println("Student Info");
for (int i = 0; i < arr.length; i++) {
System.out.println("Student[" + i + "]: " + arr[i][0] + "," + arr[i][1] + " Average: " + ComputeAvg[i]);
}
}
}

Side-note Personally, I would replace the use of the Double object by the primitive-type double, mainly because of (apart from performance) readability and because in your code is not really needed.
Create the array that will keep the average by array:
Double AddAvg[] = new Double[indexMax];
iterate through the arrays and get the average of those arrays using Java streams:
Arrays.stream(ComputeArr[i])
.mapToDouble(Double::doubleValue)
.average()
.orElse(0);
The full method:
public static Double[] ComputeAvg(Double[][] ComputeArr) {
Double[] AddAvg = new Double[indexMax];
for (int i = 0; i < indexMax; i++) {
AddAvg[i] = Arrays.stream(ComputeArr[i])
.mapToDouble(Double::doubleValue)
.average()
.orElse(0);
}
return AddAvg;
}
If you cannot use streams then do the sum manually:
public static Double[] ComputeAvg(Double[][] ComputeArr) {
Double[] AddAvg = new Double[3];
for (int i = 0; i < 3; i++) {
double sum = 0.0;
for(int j = 0; j < ComputeArr[i].length; j++) {
sum += ComputeArr[i][j];
}
AddAvg[i] = sum / ComputeArr[i].length;
}
return AddAvg;
}
In Java arrays indexed from 0 to the size of the array -1. So this method:
public static Double[][] InputGrade(Double GradeArr[][]) {
for (int i = 0; i < indexMax; i++) {
System.out.println();
System.out.println("Enter Student[" + (i + 1) + "]'s Grades");
System.out.println();
System.out.print("1st Grade: ");
GradeArr[i][2] = sc.nextDouble();
System.out.print("2nd Grade: ");
GradeArr[i][3] = sc.nextDouble();
System.out.print("3rd Grade: ");
GradeArr[i][4] = sc.nextDouble();
}
return GradeArr;
}
is accessing positions outside the boundaries of the array GradeArr (i.e., GradeArr[i][4]). Change to :
public static Double[][] InputGrade(Double GradeArr[][]) {
for (int i = 0; i < indexMax; i++) {
System.out.println();
System.out.println("Enter Student[" + (i + 1) + "]'s Grades");
System.out.println();
System.out.print("1st Grade: ");
GradeArr[i][0] = sc.nextDouble();
System.out.print("2nd Grade: ");
GradeArr[i][1] = sc.nextDouble();
System.out.print("3rd Grade: ");
GradeArr[i][2] = sc.nextDouble();
}
return GradeArr;
}

If it is possible to use Stream API, the averages of 2D Double array may be calculated using DoubleStream::average:
static Double[] calcAvg(Double[][] arr) {
return Arrays
.stream(arr) // Stream<Double[]>
.map(inner -> Arrays.stream(inner) // Stream<Double>
.mapToDouble(Double::doubleValue) // convert to primitive double
.average() // average calculated as OptionalDouble
.orElse(0.0) // in case of empty array
)
.toArray(Double[]::new);
}
Also, Collectors::averagingDouble may be used to make it even less verbose:
static Double[] calcAvg(Double[][] arr) {
return Arrays
.stream(arr) // Stream<Double[]>
.map(inner -> Arrays.stream(inner)
.collect(Collectors.averagingDouble(Double::doubleValue)) // or x -> x
)
.toArray(Double[]::new);
}
Tests
Double[][] arr = {
{},
{0.1},
{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0, 7.0, 8.0},
{5.0, 11.0, 17.0, 23.0, 29.0, 35.0},
};
System.out.println(Arrays.toString(calcAvg(new Double[0][])));
System.out.println(Arrays.toString(calcAvg(arr)));
Output:
[]
[0.0, 0.1, 2.0, 6.0, 20.0]

Related

java null and 0.0's when I print my array

When I try to print my array in the main...I'm getting NULL and 0.0.
Can anyone give me some advice as to why this may be happening?
Since I was getting all Nulls and 0.0's I pulled the for loop into my dataCalculations method and it printed the name and the sales amount perfectly.
Is my use of the .length feature incorrect?
Any advice/help would be greatly appreciated.
Thanks,
/*
* Anthony Vincenzo Laginess
* CIT 130 HMW 08 Arrays
* 10/19/16
* Time Spent:
*/
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("Please enter the total number of dealers: ");
System.out.println("------------------------------------------");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
String[] dealerNames = new String[numDealers];
double[] dealerSales = new double[numDealers];
double[] commissionRate = new double[dealerSales.length];
double[] dealershipSalesTotal = new double[dealerSales.length];
double[] dealerSalesAvgTotal = new double[dealerSales.length];
double[] totalCommission = new double[commissionRate.length];
System.out.println("--------------------------------------------------------");
System.out.printf("Please enter the required data for each of your dealers: %n");
System.out.println("--------------------------------------------------------");
dataCalculation(numDealers);
System.out.println("----------------");
System.out.println("Dealer Totals: ");
System.out.println("----------------");
displayTotals(numDealers, dealerNames, dealerSales, commissionRate);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: %n");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
double[] dealerSales = new double[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
double sales = input.nextDouble();
dealerSales[i] = sales;
}
}//data calculations
//METHOD 3
public static double[] commission(double[] dealerSales)
{
//Create array
double[] commissionRate = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
commissionRate[i] = dealerSales[i];
if(commissionRate[i] > 0 && commissionRate[i] < 5000)
commissionRate[i] = commissionRate[i] * 0.08;
else if(commissionRate[i] > 5000 && commissionRate[i] < 15000)
commissionRate[i] = commissionRate[i] * 0.15;
else if(commissionRate[i] > 15000)
commissionRate[i] = commissionRate[i] * 0.20;
}
return commissionRate;
}//commission method
public static double[] dealershipSales(double[] dealerSales)
{
//Create array
double[] dealershipSalesTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealershipSalesTotal[i] += dealerSales[i];
}
return dealershipSalesTotal;
}//dealership sales
public static double[] dealerSalesAvg(double[] dealerSales)
{
double[] dealerSalesAvgTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealerSalesAvgTotal[i] += dealerSales[i] / dealerSales.length;
}
return dealerSalesAvgTotal;
}//dealership sales averages
public static double[] dealershipTotalCommission(double[] commissionRate)
{
double[] totalCommission = new double[commissionRate.length];
for(int i = 0; i < commissionRate.length; i++)
{
totalCommission[i] += commissionRate[i];
}
return totalCommission;
}//total commission for the dealership
public static void displayTotals(int numDealers, String[] dealerNames, double[] dealerSales, double[] commissionRate)
{
for(int i = 0; i < numDealers; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
System.out.println(" " + commissionRate[i]);
}
}//display totals
}//class
You are not returning anything from dataCalculation(), so the calculations are lost when the method call is done. Just as dealerNames, dealerSales and commissionRate are passed as arguments to displayTotals(), they should probably be passed to dataCalculation() first rather than being declared again, at least the first two. You should call commission() to get the last, the method doesn’t seem to be called ever.

I'm struggling with methods...particularly the arguments that you pass it.

I'm trying to teach myself Java and I'm having a hell of a time! :)
I just started the other day and I've hit a bit of a road block.
I'm trying to learn arrays, but my methods are also kinda jacked up.
I know when I invoke my method in my main that it isn't right. I thought I was supposed to give the method that I was invoking the arguments that it needs to carry out its processes?
I'm just trying to call my last method and display the data from that method.
package test_arraymethods;
import java.util.Scanner;
public class TEST_arraymethods
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("------------------------------------------");
System.out.println("Please enter the total number of dealers: ");
System.out.println("------------------------------------------");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.println("--------------------------------------------------------");
System.out.printf("Please enter the required data for each of your dealers: %n");
System.out.println("--------------------------------------------------------");
dataCalculation(numDealers);
//displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: %n");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
double[] dealerSales = new double[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
double sales = input.nextDouble();
dealerSales[i] = sales;
}
}//data calculations
//METHOD 3
public static double[] commission(double[] dealerSales)
{
//Create array
double[] commissionRate = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
commissionRate[i] = dealerSales[i];
if(commissionRate[i] > 0 && commissionRate[i] < 5000)
commissionRate[i] = commissionRate[i] * 0.08;
else if(commissionRate[i] > 5000 && commissionRate[i] < 15000)
commissionRate[i] = commissionRate[i] * 0.15;
else if(commissionRate[i] > 15000)
commissionRate[i] = commissionRate[i] * 0.20;
}
return commissionRate;
}//commission method
public static double[] dealershipSales(double[] dealerSales)
{
//Create array
double[] dealershipSalesTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealershipSalesTotal[i] += dealerSales[i];
}
return dealershipSalesTotal;
}//dealership sales
public static double[] dealerSalesAvg(double[] dealerSales)
{
double[] dealerSalesAvgTotal = new double[dealerSales.length];
for(int i = 0; i < dealerSales.length; i++)
{
dealerSalesAvgTotal[i] += dealerSales[i] / dealerSales.length;
}
return dealerSalesAvgTotal;
}//dealership sales averages
public static double[] dealershipTotalCommission(double[] commissionRate)
{
double[] totalCommission = new double[commissionRate.length];
for(int i = 0; i < commissionRate.length; i++)
{
totalCommission[i] += commissionRate[i];
}
return totalCommission;
}//total commission for the dealership
public static void displayTotals(double[] numberOfDealers, double[] dealerNames, double[] dealerSales, double[] commissionRate)
{
for(int i = 0; i < numberOfDealers.length; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
System.out.println(" " + commissionRate[i]);
}
// pass all of your values to this method and then display them
//display the dealer name and amount of sales
//and the amount of commission for all dealers in a tabular format.
}//display totals */
}//class
The reason that you can't get this to work:
displayTotals(numberOfDealers, dealerNames, dealerSales, commissionRate);
is that it is referring to variables that are not in scope. Those variables are all local variables within methods whose calls have finished. If you want the variables to be accessible in another method, they must be declared as (static, in this case) fields.

How to convert an String Variable with Array to an Integer Variable with Array

I am new to java programming. I am trying to convert an string variable with array to an int variable array
but i have 2 errors and have no idea to fix it,
any help would be great, thanks..
This is my source code :
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int sum=0;
for(x=0;x<=1;x++)
{
System.out.print("input number : ");number[x]=in.next();
int value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum+number[x];
}
for(x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
This is what the errors look like
when you convert an array of stirngs to an array of integers,
we should have an array of integers declared
and in the code that you posted there are some syntax errors because you didnt declare integer array before use(int value[x])
and try the below code which will convert string array of numbers(string number[]) into an ineger array of numbers(int value[])
import java.util.Scanner;
public class stringtoint {
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100]; // here I declared an array of integers with the name value
int sum=0;
for(int x= 0;x <= 1; x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]); // i found "expected here", what should i do, need help, please..
sum=sum + value[x];
}
for(int x=0; x<=1; x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
}
Use in.nextInt() method.
Scanner in = new Scanner(System.in);
int number[] = new int[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {`enter code here`
System.out.print("input number : ");
number[x] = in.nextInt();
sum = sum + number[x];
}
System.out.println("Sum :\t " + sum);
in.close();
}
Create a int array, then use it. int value[x]= Integer.parseInt(number[x]); is an error because your are trying to assign an integer to an array.
Correct one may be...
public static void main (String args[]) {
Scanner in=new Scanner(System.in);
String number[]=new String[100];
int value[]= new int[100];
int sum=0;
for(int x=0;x<=1;x++)
{
System.out.print("input number : ");
number[x]=in.next();
value[x]= Integer.parseInt(number[x]);
sum=sum+value[x];
}
for(int x=0;x<=1;x++)
{
System.out.println("Data Number "+(x+1)+" : "+number[x]);
}
System.out.println("Sum :\t "+sum);
}
There seems problem with declaration and usage of variable in you sample code.
Variable x is not initialzed
An integer value is assigned to and array declaration.
Try the below code to solve your issues.
import java.util.Scanner;
public class stringtoint {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
for (int x = 0; x <= 1; x++) {
System.out.print("input number : ");
number[x] = in.next();
int value = Integer.parseInt(number[x]);
sum = sum + value;
}
for (int x = 0; x <= 1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
in.close();
}
}
public static void main(String args[]) {
String[] exampleOfStringArray = {"11", "22", "33"/*, "ab", "cd", "ef", "", null*/};
int[] intArray = getIntArray(exampleOfStringArray);
int sum = getSumOf(exampleOfStringArray);
}
private static int[] getIntArray(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).toArray();
}
private static int getSumOf(String... stringArray) /*throws NumberFormatException*/ {
return Arrays.<String>asList(stringArray).stream().mapToInt(Integer::parseInt).sum();
}
Try below code, it is working.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String number[] = new String[100];
int sum = 0;
int noOfInputs = 2;
int value[] = new int[noOfInputs];
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.print("input number : ");
number[x] = in.next();
value[x] = Integer.parseInt(number[x]);
sum = sum + value[x];
}
for (int x = 0; x <= noOfInputs-1; x++) {
System.out.println("Data Number " + (x + 1) + " : " + number[x]);
}
System.out.println("Sum :\t " + sum);
}

How can I fix this "OutOfBoundaryException" error?

import java.util.Scanner;
class DataInput {
String name[];
int korean[], math[], english[];
int sum[];
double average[];
int students;
int rank[];
public void save() {
Scanner sc = new Scanner(System.in);
System.out.println("Type in number of students");
students = sc.nextInt();
name = new String[students];
korean = new int[students];
math = new int[students];
english = new int[students];
sum = new int[students];
average = new double[students];
rank = new int[students];
for (int i = 0; i < students; i++) {
System.out.println("Type name");
name[i] = sc.next();
System.out.println("Type Korean score");
korean[i] = sc.nextInt();
System.out.println("Type math score");
math[i] = sc.nextInt();
System.out.println("Type English score");
english[i] = sc.nextInt();
sum[i] = korean[i] + math[i] + english[i];
average[i] = sum[i] / 3.0;
}
}
int stu() {
return students;
}
int[] sum() {
return sum;
}
}
class DataOutput {
DataInput data = new DataInput();
int sNum;
int[] rrank, sum;
DataOutput(int students, int[] sum) {
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
void ranker() {
int cnt = 1;
for (int i = 0; i < sNum; i++) {
for (int j = 0; j < sNum; j++) {
if (sum[i] < sum[j]) {
cnt++;
}
}
rrank[i] = cnt;
cnt = 1;
}
}
}
public class Score {
public static void main(String[] args) {
DataInput data = new DataInput();
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
data.save();
out.ranker();
System.out.println();
System.out.println("Name\t\tKorean math English \t sum Average Rank");
System.out
.println("-------------------------------------------------------");
for (int i = 0; i < data.stu(); i++) {
System.out.println(data.name[i] + "\t\t" + data.korean[i] + " "
+ data.math[i] + " " + data.english[i] + "\t"
+ data.sum[i] + " " + data.average[i] + " "
+ out.rrank[i]); // this is where i get an Exception
}
}
}
So, this is my program for getting ranks of students. But somehow when I run the code, I keep getting "OutOfBoundaryException". I checked my code, and realized that when I instantiate a new instance of DataOutput, it creates all new data. So I tried to fix this by setting a constructor. However I still can't solve this matter. I know that I can put the ranker method into DataInput class, and problem will be easily solved however I really want to keep DataOutput class.
Thank you for your time.
PS: Exception is thrown on line 98, out.rrank[i]
Your students field isn't set until the save() method is called. The value of sNum in main is then 0.
Change the order in main to:
DataInput data = new DataInput();
data.save();// <--
int sNum = data.stu();
int[] sum = data.sum();
DataOutput out = new DataOutput(sNum, sum);
out.ranker();
the problem was that you initialize the rank[] before creating students, As soultion I suggest you to initialize after collection students/scores
public void init(int students, int[] sum){
this.sNum = students;
this.rrank = new int[sNum];
this.sum = sum;
}
And update main()
DataOutput out = new DataOutput();
data.save();
int sNum = data.stu();
int[] sum = data.sum();
out.init(sNum, sum);
out.ranker();

ArrayIndexOutOfBoundsException large number adding program

I am working on a large number adding program (without using biginteger class). I thought I had this understood but for some reason I am getting an ArrayIndexOutOfBoundsException for my add method:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at LargeInteger.add(LargeInteger.java:50)
at testLargeInteger.main(testLargeInteger.java:32)
main:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
public LargeInteger( int[] array ) {
intArray = array;
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
//get first array
public int[] getIntArray() {
return intArray;
}
public LargeInteger add(LargeInteger secondInt){
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++) {
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
return new LargeInteger( resultArray );
}
}
Here you declare the array with length:
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
and here you access it using the same length:
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
In Java (and computer languages generally), the array indices begin at 0 and end at length - 1. So if you declare an array 10 elements long, then the indices are 0-9. Therefore you must substract one:
resultArray[Math.max(intArray.length, otherValues.length)] = needToAdd;
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
arrays in java starts from 0, and your allocated space is exactly the same ammount of elements:
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
So, you get an out of index, since you access one element out of the array.

Categories

Resources