Java Loop or Arrays - java

My problem is based on the compound interest formula. A = P(1 + r)^n. I have a number of values for r and n which I must store as an array. I also must output my range of final values A as an array also. I think I have stored r and n correctly as an array. However my problem is with the final values of A and storing each value A. SO far this is what I have written.
import java.util.Scanner;
import javax.swing.*;
public class Prin {
public static void main (String [] args){
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner (System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1,2,3,4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
amountarray = new double[19];
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
}
}
Do I need another for loop to increase the values of k in amountarray[]?
I would like to have all values of amountarray i.e amountarray[0], amountarray[1], amountarray[2], .......and so on.
Thanks in advance for any help.

amountarray = new double[19];
The code above is false because you need to have 4x5 = 20 double values
This code will always work properly, You should use this and you need to learn write your codes like this:
public class Prin {
public static void main (String [] args){
//...
int[] yearsarray = {1,2,3,4};
double[] ratearray = {0.010, 0.015, 0.020, 0.025, 0.030};
double[] amountarray = new double[yearsarray.length * ratearray.length];
int k = 0;
for(int i=0; i<yearsarray.length; i++){
for(int j=0; j<ratearray.length; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
k++;
}
}

"This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%"
... this implies your answer comes in the form of a 2-dimensional matrix.
Hence your amountarray needs to be defined as:
double amountarray[][] = new double[yearsarray.length][ratearray.length];
Then you would calculate:
amountarray[i][j] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);

No, you don't
int k=0; // initialization
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
// now we can increment k
k = k+1;
}
Also this: as you seem to be using yearsarray just to get a value that's i+1, why just not do
amountarray[k] = principal * Math.pow((1 + ratearray[j]), i+1);
That way you can get rid of yearsarray, at least in this case
EDIT: a reworked version that also handles a couple of other minor issues and reduced usage of "magic numbers"
public class Prin {
public static void main(String[] args) {
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner(System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1, 2, 3, 4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
// this way the array will follow the size of yearsarray and ratearray
amountarray = new double[yearsarray.length * ratearray.length];
int k = 0; // initialization
for (int i = 0; i <= yearsarray.length; i++) {
System.out.println("years=" + yearsarray[i]);
for (int j = 0; j < ratearray.length; j++) {
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" " + ratearray[j] + " answer " + amountarray[k]);
k+=1;
}
}
}
}

Try to store your data in a Map, this is an example of your loop
for(int i=0; i<=yearsarray.length; i++) {
for(int j=0; j<=ratearray.length; j++) {
double answer = (yearsarray, principal * Math.pow((1 + ratearray[j]), yearsarray[i]));
Collection<Double> aux;
if (!answers.containsKey(yearsarray[i])){
aux = new ArrayList<Double>();
aux.add(answer);
} else {
aux = answers.get(yearsarray[i]);
aux.add(answer);
}
answers.put(yearsarray[i], aux);
// include the answers in a Map
}
}
Thanks

Related

find probability of n people in a class of x share the same birthday using monte carlo simulation in java

As the problem states, i must use monte carlo(randomness) to solve the question given. I am running the simulation 1,000,000 times.
import java.util.*;
public class MonteCarlo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter size of the class: ");
int classSize = sc.nextInt();
System.out.println("Please enter the amount of people who share the same birthday: ");
int birthPpl = sc.nextInt();
System.out.println("calculate the probability that "+birthPpl+" people share the same Birthday in a class size of "+classSize);
sc.close();
int birthdays [] = new int[classSize];
int simulations = 0;
int success=0;
for(int i=0; i<1000000; i++){
simulations++;
if(Collision(birthdays)>=birthPpl){
success++;
}
}
System.out.println(success+" "+simulations);
System.out.println("Answer: "+ (success*100)/simulations + "%");
}
public static int Collision(int birthday[]){
Random rand = new Random();
for(int i=1; i<birthday.length; i++){
birthday[i]= rand.nextInt(365);
}
int count = 0;
for(int i=0; i<birthday.length; i++){
for(int j= i+1; j<birthday.length; j++){
if(birthday[i]==birthday[j]){
count++;
}
}
}
return count;
}
}
As per a couple of psuedo code solutions i have seen online i have tried looping through the size of the class x and inserting in a random birthday. then comparing birthdays , reducing the birthdays i look through by 1 each time. I then check the number of collisions against the amount sof ppl who should a birthday , if it is greater or equal to it than i increase the count. i have been given sample imput 20 and 2 which should give 41 % but my program gives eithe 7 or 8 %
What's the problem, and how can it be fixed?
You could also make use the Random and HashMap classes. Map.merge will take the key, a birthday in this case, then a default value of 1, and continues to add 1 to the existing value which is returned and compared to x. Then success is appropriately updated. The Random class provides a variety of methods to return random numbers and is usually preferred over Math.random.
double success = 0;
int tests = 1_000_000;
// instantiate a Random class for selecting the next birthday
Random r = new Random();
// a map to hold the frequency count of same birthdays
Map<Integer,Integer> birthdays = new HashMap<>();
int n = 23;
int x = 2;
for(int i=0; i< tests; i++) {
for (int j = 0; j < n; j++) {
if (birthdays.merge(r.nextInt(365), 1, Integer::sum) >= x) {
success++;
break;
}
}
// clear the map for the next run
birthdays.clear();
}
Using System.out.printf facilitates formatting the output.
System.out.printf("probability = %4.1f%%%n", (success/tests) * 100);
prints something like the following:
probability = 50.7%
import java.util.Scanner;
public class Birthday {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // class size
int x = sc.nextInt(); // people who share the same birthday
double tests = 1_000_000;
double success = 0;
// fills array of birthdays and breaks out when x amount of people share
// a birthday. then we find the % of successes.
for (int i = 0; i < tests; i++) {
int[] year = new int[365];
for (int j = 0; j < n; j++) {
int birthday = (int) (Math.random() * 365);
year[birthday]++;
if (year[birthday] >= x) {
success++;
break;
}
}
}
System.out.println(Math.round(success * 100 / tests));
}
}

Program ignoring the last row in the file in calculation

I have a text file with data that looks like this (TestData.txt):
Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
Richard Perez|100|84|73|81|92|84|95|96|95|100
Ivan Dyer|77|91|90|75|97|94|76|89|90|92
Craig Palmer|91|84|98|89|82|75|78|96|100|97
Madeline Rogers|75|79|78|93|91|76|80|88|100|81
Chelsea Roxas|87|94|89|96|95|85|88|92|86|86
Jasper Bautista|100|83|93|100|98|97|96|97|97|98
Tyler Perez|82|89|90|78|89|96|75|88|90|96
My code parses the file and does some calculations with it.
However, in the method arrangeList() within which calls another method called getTestAvg() (calculates column means), the program ignores Tyler Perez's scores.
I noticed that the results I am getting were inaccurate so I went and printed the whole 2d array with all the test scores and the last column is nowhere to be found.
My entire code is below and I hope someone could point out what causes this.
I keep getting an IndexOutOfBounds error whenever I try to switch N (# of students) and M (# of tests) to see what happens. At first, I have 10 students and 10 tests, and all the calculations were correct, but when I added another student, the calculations became inaccurate.
I apologize in advance if my code isn't as well-designed as I'm not an experienced programmer.
import java.util.*;
import java.io.*;
public class TestAverages
{
private static int[] grades;
private static int[] testTotal;
private static int N;
private static double classTotal;
private static int M;
public static void main(String[] args) throws FileNotFoundException
{
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException
{
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
int index = 0;
while(in.hasNextLine())
{
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
N = grades.length;
for(int i = 0; i < N; i++){
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double)grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
M++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades)
{
double total = 0.0;
double avg = 0.0;
int N = grades.length;
for(int i = 0; i < N; i++){
total += grades[i];}
avg = total / N;
return avg;
}
public double getClassAvg(double total)
{
double classAvg = total / M;
return classAvg;
}
public double[][] arrangeList(ArrayList testScores)
{
double[][] tests = new double[N][N];
int len = tests.length;
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
for(int i = 0; i < len; i++)
{
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index)
{
double testAvg = 0.0;
for(int i = 0; i < N; i++)
{
testAvg += testScores[i][index];
}
return testAvg / N;
}
}
Here are the numbers I'm supposed to be getting (top) compared to what my program outputs (bottom).
As the other responses already stated, you had quite the issue with your variables and loops. I now changed N to # of students and M to # of tests to be as you stated in your question.
Next time, maybe try to improve your variable naming, so you don't get confused. (e.g. switch out n and m for s (students) and t (tests), if you like your variable names short).
This should work now. Just check against your code to see the changes.
import java.util.*;
import java.io.*;
public class TestAverages {
private static int[] grades;
private static int n = 0; // amount of students
private static int m; // amount of tests
public static void main(String[] args) throws FileNotFoundException {
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException {
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
while (in.hasNextLine()) {
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
m = grades.length;
for (int i = 0; i < m; i++) {
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double) grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
n++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades) {
double total = 0.0;
double avg = 0.0;
for (int i = 0; i < grades.length; i++) {
total += grades[i];
}
avg = total / grades.length;
return avg;
}
public double getClassAvg(double total) {
double classAvg = total / n;
return classAvg;
}
public double[][] arrangeList(ArrayList<Double> testScores) {
double[][] tests = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tests[i][j] = (Double) testScores.get(i * m + j);
}
}
for (int i = 0; i < m; i++) {
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index) {
double testAvg = 0.0;
for (int i = 0; i < n; i++) {
testAvg += testScores[i][index];
}
return testAvg / n;
}
}
You need to account for the different sizes. I think you want primarily the number of TESTS (not students), but you can't just use len for both index bounds.
double[][] tests = new double[N][M];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
Note that it didn't just resize the array, but it changed the loop conditions to loop the proper amount for inner and outer loop.
In the line
double[][] tests = new double[N][N];
of function arrangeList
you make your test array as N X N.
I believe youh should do something like
double[][] tests = new double[M][N];
It's just a suggestion as in your code it seems M = number of students and N = number of tests, differently from what you write in your question.
In general you should review all the method arrangeList and probably getTestAvg too (loop on N, instead of M), as the loops on variable len are intended for a N X N array, which is not the case.

Java is printing last number using array method, by ignoring other numbers

I'm trying to let my code print numbers I put in output but using array method.
package pkg11;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
for (int z = 1; z <= b; z++) {
System.out.println("Input your" + " " + z + " " + "number");
x = in.nextInt();
}
System.out.println();
int[] a = new int[x];;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The problem is when it's printing it only prints the last value, for example, I put that I want to put 3 numbers, the first was 1 the second was 2 the third was 3, it prints the third without putting the first 2.
Have a close look at the following code fragment of yours and try to spot the error:
for (int z = 1; z <= b ; z++) {
System.out.println("Input your" +" " +z +" " +"number");
x = in.nextInt();
}
// here you create the array
int [] a = new int [x];
If you didnt spot it: You create the array you want to save each integer in after you have read all values from the console. There is no way you can store the users input in the array, since it is not known at that time.
Then, what did you actually do?
You used the same variable x all the time x = in.nextInt();, overriding each input.
What can i do to solve the problem?
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
int[] a = new int[b];
for (int z = 0; z < b; z++) {
System.out.println("Input your" + " " + (z + 1) + " " + "number");
a[z] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
First, declare int[] a = new int[b]; before you read the values and assign each input the the array with a[z] = in.nextInt();. Also, i modified your loop index a little bit to make things easier.
Ok, what else can i do?
Apart from the user entering non numbers, this code is a little bit more bullet-proof! If you are looking for even more, you can use in.nextLine() and Integer.valueOf() to prevent the user from entering strings instead of numbers.
Scanner in = new Scanner(System.in);
int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");
amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
System.out.println("Please enter a number greater than one:");
amountOfNumers = in.nextInt();
}
int[] numbers = new int[amountOfNumers];
for (int i = 0; i < amountOfNumers; i++) {
System.out.println("Input your " + (i + 1) + " number: ");
numbers[i] = in.nextInt();
}
System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);

java if statement in array for loop

Alright so I need to add some additional functions to this array, which gives 10 random integers. It needs to be able to store the numbers that are less than 40 and print them along with the numbers that are less than the average. How do I do this with an if statement in a for loop? (Ignore the stuff that's cometted out.
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
for(int i=0; i<ages.length; i++){ //adds stuff to arrays
ages[i] = gen.nextInt(100); //Determines the maximum used in random number generation
}
for(int x=0; x<10; x++){//prints the array with the below statement
System.out.println(ages[x]);
}
System.out.println("---------------");
System.out.println(ages[9]);
System.out.println(ages[8]);
System.out.println(ages[7]);
System.out.println(ages[6]);
System.out.println(ages[5]);
System.out.println(ages[4]);
System.out.println(ages[3]);
System.out.println(ages[2]);
System.out.println(ages[1]);
System.out.println(ages[0]);
int value = (ages[0] + ages[1] + ages[2] + ages[3] + ages[4] + ages[5] + ages[6] + ages[7] + ages[8] + ages[9]);
System.out.println("The combined value of the integers is " + value + ".");
int average = (value / 10);
System.out.println("The average value of the integers is " + average + ".");
}
}
Something like that? (Sorry guys for code but i don't have a time to make it better):
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
List<Integer> agesLesserThan40 = new ArrayList();
List<Integer> agesLesserThanAverage = new ArrayList();
float value = 0;
for(int i=0; i<10; i++) {
ages[i] = gen.nextInt(100);
value += ages[i];
}
for(int x=0; x<10; x++){
if(ages[x] < value/10) agesLesserThanAverage.add(ages[x]);
if(ages[x] < 40) agesLesserThan40.add(ages[x]);
}
System.out.println("ages:");
for(int z=0; z<10; z++){System.out.print(ages[z] + ", ");}
System.out.println();
System.out.println("Lesser than 40: ");
for(int y=0; y<agesLesserThan40.size()-1; y++){System.out.print(agesLesserThan40.get(y) + ", ");}
System.out.println();
System.out.println("Lesser than average: ");
for(int y=0; y<agesLesserThanAverage.size()-1; y++){System.out.print(agesLesserThanAverage.get(y) + ", ");}
System.out.println();
System.out.println("The average value of the integers is " + value / 10 + ".");
System.out.println("The combined value of the integers is " + value + ".");
}
}
I have no idea how if (value >= 100000) says anything is less than 40...
Here is probably how you could divide your array into above and under 40.
final int AGES_TO_GENERATE = 10;
final int AGE_LIMIT = 100;
final int AGE_DIVIDER = 40;
List<Integer> lesserAge = new ArrayList<>();
List<Integer> upperAge = new ArrayList<>();
Random gen = new Random();
double averageAge = 0.0;
for(int i=0; i<AGES_TO_GENERATE; i++){
int age = gen.nextInt(AGE_LIMIT);
averageAge += age;
if (age < AGE_DIVIDER) lesserAge.add(age);
else upperAge.add(age);
}
averageAge /= AGES_TO_GENERATE;
System.out.println("Here are the values less than 40");
System.out.println(lesserAge);
if (upperAge.isEmpty()) {
System.out.println("There are no values over 40");
}
If using Java 8, you can print values less than the average very simply
lesserAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);
upperAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);

Adding elements in an array in a loop

I'm only a beginner, so I know data structure and code logic isn't very good at all.
So this is a portion of a project, but I am having difficulty formatting the for loop. I am pretty sure I have to create some kind of for each loop. I wasn't sure how to do it, so I created a very simplified and broken down version (I know most of the code is in practice, but I wanted to visualize it. I need help printing out the total sales for each category of product. Right now, I only have four values, but if I were to go up to 30 values, this code would not work obviously. So any tips on how to create the for loop?
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
totalSale[1] = totalSale[1] + iphone[i];
totalSale[2] = totalSale[2] + ipad[i];
totalSale[3] = totalSale[3] + ipod[i];
}
for (int i = 0; i < totalSale.length; i++) {
System.out.println("Total sale for category " + i + ": $" +
}
return totalSale;
}
Change
for (int i = 0; i < totalSale.length; i++) {
if (i == 0) {
System.out.println("Total sale for category " + i + ": $" + totalSale[0]);
}
if (i == 1) {
System.out.println("Total sale for category " + i + ": $" + totalSale[1]);
}
if (i == 2) {
System.out.println("Total sale for category " + i + ": $" + totalSale[2]);
}
if (i == 3) {
System.out.println("Total sale for category " + i + ": $" + totalSale[3]);
}
}
to
for (int i = 0; i < totalSale.length; i++) {
System.out.println("Total sale for category " + i + ": $ + totalSale[i]);
}
There's no need to create an if-statement for every single element in the array totalSale. Think about general cases for the array when dealing with loop statements involving arrays. Since you're printing out every single element in the array with the same line "Total sale for category", you can toy with it and think about what's changing and what isn't.
Clearly, the only things changing are i and the element in the array that's being printed out. What's changing can be represented by variables (i, totalSale[i]) and what's not changing can be represented by constants ("Total sale for category", "$"). Therefore, you only need one line in your for-loop to express this when printing out elements of an array.
EDIT: A way to deal with the problem of accepting a variable number of sales categories in your method is to instead make your method take in a 2D array, in which the number of rows is the number of categories and the number of columns ins the number of sales within each category. For example, int sales[][] = new int[30][20] represents an array of 30 categories with 20 sales in each category. So modify the header,
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod )
to
public static int[] totalSale(int[][] sales)
and change this,
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
totalSale[1] = totalSale[1] + iphone[i];
totalSale[2] = totalSale[2] + ipad[i];
totalSale[3] = totalSale[3] + ipod[i];
}
to
int[] totalSale = new int[sales.length];//sales.length is the number of
//rows/categories in sales
for (int i = 0; i < sales.length ; i++) {
for (int j = 0; j < sales[i].length; j++) { //sales[i].length is the number
//of sales/columns per category
totalSale[i] = totalSale[i] + sales[i][j];//sales[i][j] is the jth
//sale in the ith category
}
}
And lastly in the main, those 4 arrays can now be replaced with a 2D array.
Replace,
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
with
int[][] sales = { {200,9000,13000,900},
{500,5000,200,0},
{900,4300,0,800},
{0,300,120,500}}; //how you define a 2D array
Above is a 4x4 array but it can be flexible. You can make it 10x10, 20x20, 30x30, etc.
Lastly, don't forget to change the method call to take in only one parameter now, the 2D array.
Change
popularDay(days,mac,iphone,ipad,ipod);
to
popularDay(sales);
Here, i can see that you are assuming mac, iphone, ipad and ipod arrays will always have the same number of elements (length). Your code can break in the case one of them have a different length.
I would rather suggest this approach:
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
}
for (int i = 0; i < iphone.length ; i++) {
totalSale[1] = totalSale[1] + iphone[i];
}
for (int i = 0; i < ipad.length ; i++) {
totalSale[2] = totalSale[2] + ipad[i];
}
for (int i = 0; i < ipod.length ; i++) {
totalSale[3] = totalSale[3] + ipod[i];
}
System.out.println("Total sale for category mac: $" + totalSale[0]);
System.out.println("Total sale for category iphone: $" + totalSale[1]);
System.out.println("Total sale for category ipad: $" + totalSale[2]);
System.out.println("Total sale for category ipod: $" + totalSale[3]);
return totalSale;
}
First, calculate the total sale for each category by its own, using a for loop for each of them. Then writing the result back to the console without the for loop, since it has no reason to be used.
Varargs will help you:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
public static int[] totalSale(int[]... categories) {
int[] totalSale = new int[categories.length];
for (int i = 0; i < totalSale.length; i++) {
for (int j = 0; j < categories[i].length; j++) {
totalSale[i] = totalSale[i] + categories[i][j];
}
System.out.println("Total sale for category " + i + ": $" + totalSale[i]);
}
return totalSale;
}
So, in this case you can either to pass any amount of parameters:
int[] totalSales = totalSale(mac, iphone, ipad, ipod, ipod2, iphone3, iphone4);
int[] totalSales2 = totalSale(ipod, ipod2, iphone3, iphone4);
Or make an array to pass only one parameter using the same method:
int[][] categories = {mac, iphone, ipad, ipod, ipod2, ipod3, iphone100500};
int[] totalSales2 = totalSale(categories);
And if you want use only the second way, then you can just define the method as:
public static int[] totalSale(int[][] categories)
I suppose you requirement is SUM all array data as below and store the result into the array too?
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
int[] result equal to {macSUM, iphoneSUM, ipadSUM, ipodSUM}
So we can use two loops one if for each device, and other one is for each element in the array the code show below as example
public static int totalSale(int[] devices){
int sum;
for (int i = 0; i < devices.length ; i++) {
sum += devices[i];
}
return totalSale;
}
public static void main(String[] arguments) {
int[] days = {1,2,3,4};
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
numberOfDays(days);
int[]totalSales = new int[4];
for(int i = 0; i < 4; i++) {
totalSales[i] = totalSale(mac);
}
}

Categories