How to make methods take in arrays from the main method? - java

What I need to do is make the main method give an array that the other two methods have. The code works, but the numbers are just in the wrong place.
Everything I've tried has given me an exception and I'm not sure what to do.
public static void main(String[] args) {
arrayTotalAndAverage(null); //not sure what to put in the parenthesis, it was corrected to be null
arrayTwoDimTotalAndAverage(null);
}
public static void arrayTotalAndAverage(int[] array) {
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209}; //I need to move these numbers to the main method and I'm not sure how to leave it, is it "int[] numbers = {}"?
int total = 0;
double average = 0; //is this right?
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
public static void arrayTwoDimTotalAndAverage(int[][] array) {
int[][] numbers = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
average = total / numbers.length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}

A simple example of how to send an array and receive them from another place is like this:
We have our array outside, then you pass it as parameter to your method, where you're expecting an int[] parameter, then you can make use of it with parameter variable name inside that method.
For example:
public class ArrayAsParametersExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
printNumbersFromArray(numbers);
}
private static void printNumbersFromArray(int numbersArray[]) {
for (int n : numbersArray) {
System.out.println(n);
}
}
}

You can make your main function look like:
public static void main(String[] args){
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
arrayTotalAndAverage(numbers);
}
And do similarly for your other method.

Change arrayTwoDimTotalAndAverage like this.
public static void arrayTwoDimTotalAndAverage(int[][] array) {
int[][] numbers = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
int count = 0;
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
count += numbers[row].length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
average = total / count;
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}

Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
So Instead of defining the array in each method, we can initialize the array in the main method, which we can then pass to the candidate methods as a parameter.
Try this:
public static void main(String[] args) {
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
int[][] numbers2 = { { 11, 17, 24 }, { 49, 57, 78 }, { 677, 173, 923 } };
arrayTotalAndAverage(numbers);
arrayTwoDimTotalAndAverage(numbers2);
}
public static void arrayTotalAndAverage(int[] numbers) {
int total = 0;
double average = 0; //is this right?
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
public static void arrayTwoDimTotalAndAverage(int[][] numbers) {
int total = 0;
double average = 0;
int highest = numbers[0][0];
int lowest = numbers[0][0];
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[row].length; col++) {
total += numbers[row][col];
average = total / numbers.length;
if (numbers[row][col] > highest)
highest = numbers[row][col];
if (numbers[row][col] < lowest)
lowest = numbers[row][col];
}
}
System.out.println("2D Total");
System.out.println(total);
System.out.println("2D Average");
System.out.println(average);
System.out.println("2D Highest number");
System.out.println(highest);
System.out.println("2D Lowest number");
System.out.println(lowest);
}

Related

How to do multiple Array Operations using a single for loop?

so I'm being instructed to do the following, I can get it to run just fine, but it needs to be done with only a single for loop and I just can't figure out how to do it. Any help would be appreciated. This is what I came up with. I need to be able to get the Total, Average, Highest number and lowest number with one for loop.
public static void arrayTotalAndAverage(int[] array) {
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int total = 0;
double average = 0;
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
average = total / numbers.length;
}
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
You can do all this operations by StreamAPI.
int[] numbers = {10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209};
IntSummaryStatistics statistics = IntStream.of(numbers).summaryStatistics();
System.out.println("total: " + statistics.getSum());
System.out.println("average: " + statistics.getAverage());
System.out.println("minimum: " + statistics.getMin());
System.out.println("maximum: " + statistics.getMax());
Actually, perhaps the most efficient way to proceed here would be to just iterate the array once, and then keep track of state for the minimum, maximum, average, and total:
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int total = 0;
double average = 0;
for (int i=0; i < numbers.length; ++i) {
total += numbers[i];
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
average = 1.0d * total / numbers.length;
System.out.println("total: " + total);
System.out.println("average: " + average);
System.out.println("minimum: " + min);
System.out.println("maximum: " + max);
This prints:
total: 1087
average: 72.46666666666667
minimum: 3
maximum: 212
You can do all the operations in single loop like this. And the average can be moved out of the loop.
int[] numbers = { 10, 4, 13, 29, 57, 92, 114, 212, 3, 88, 36, 101, 77, 42, 209 };
int total = 0;
double average = 0;
int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
average = total / numbers.length;
System.out.println("Total");
System.out.println(total);
System.out.println("Average");
System.out.println(average);
System.out.println("Highest number");
System.out.println(highest);
System.out.println("Lowest number");
System.out.println(lowest);
}
You can simply merge your second loop with the first one. Note that you should only calculate average at the end of the loop and one of the operands must be cast to double first to avoid the truncation of integer division.
int total = 0;
double average = 0;
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
if (numbers[i] > highest)
highest = numbers[i];
if (numbers[i] < lowest)
lowest = numbers[i];
}
average = (double) total / numbers.length;
Demo
Output:
Total
1087
Average
72.46666666666667
Highest number
212
Lowest number
3

How to find the highest Total value index in the Array?

here fundememtal,database are two subjects. same element's on both
arrays are for the same student. ( fundemental[0],database[0]--> this
is for the student 1 ) . i need to find highest(high rank) to lowest
rank students from this program.i declare a sort method and pass the
total array and create that array total as ascending.just check it out my attachment photo.
i need to find this rank
here is my code.if anybody have unclear, please ask me.
import java.util.*;
class Remove{
public static void main(String args[]){
int [] fundemental={54,34,35,65,87,37};
int database[]={67,56,45,57,78,89};
int[] total=new int[database.length];
for (int i = 0; i < database.length; i++){
total[i]=fundemental[i]+database[i];
}
int [] arrayTot=sort(total);
int index=0;
for (int i = 0; i < total.length; i++){
for (int j = 0; j < total.length; j++){
if(total[i]==(fundemental[j]+database[j]))
index=i;
}
}
}
public static int[] sort(int[]total){
for (int i = total.length; i >0; i--){
int min=total[0];
int index=0;
for (int j =1; j < i; j++)
{
if(total[j]<min){
min=total[j];
index=j;
}
}
total[index]=total[i-1];
total[i-1]=min;
}
return total;
}
}
if anybody has an another idea for find highest rank to lower rand from
student's two subject, please code me.
You can use insertion sort to the small array size and swap all arrays
public static void main(String[] args) {
int[] fundamentals = { 54, 34, 35, 65, 87, 37 };
int database[] = { 67, 56, 45, 57, 78, 89 };
int len = database.length;
int[] total = new int[len];
for (int i = 0; i < len; i++) {
total[i] = fundamentals[i] + database[i];
}
for (int i = 1; i < len; i++) {
for (int j = i; j > 0 && total[j] > total[j - 1]; j--) {
swap(total, fundamentals, database, j, j - 1);
}
}
}
static void swap(int[] total, int[] fundamentals, int[] database, int i, int j) {
int temp = total[j];
total[j] = total[i];
total[i] = temp;
temp = fundamentals[j];
fundamentals[j] = fundamentals[i];
fundamentals[i] = temp;
temp = database[i - 1];
database[i - 1] = database[i];
database[i] = temp;
}
, output
[165, 126, 122, 121, 90, 80]
[87, 37, 65, 54, 34, 35]
[78, 89, 57, 67, 56, 45]

Determine which column contains the maximum sum of its elements

I would like to know, how to find out which column in the 2D-array has got the largest sum. How would I approach this?
public static void main(String args[]) {
int[][] array = {
{ 132, 154, 118 },
{ 355, 101, 50 },
{ 432, 143, 365 },
{ 462, 234, 185 }
};
}
You could go with a nested for loop
int maxCol = 0;
int valOfMaxCol = 0;
for(int i = 0; i < 3; i++){
int sum = 0;
for(int j = 0; j < array.length; j++){
sum += array[j][i];
}
if(sum > valOfMaxCol){
valOfMaxCol = sum;
maxCol = i;
}
}
System.out.println("Max Col is " + (maxCol + 1) + " with the value " + valOfMaxCol);

How do I fix my addition for summing a specific row and column in java?

I have all of my other methods that were required for my class program working properly, however I can not think of how to fix my row input and sum method and my column input and sum method. I also apologize for the ridiculously long method names, the methods for pre-named for the assignment.
import java.util.Scanner;
public class Two_D_Array_CMPS280_2016
{// begin class Two_D_Array_CMPS280_2016
public static void main(String args[])
{// begin main method
int[][] brianArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};// end array initialization
// Print segment to print values from methods for brianArray
System.out.print("The sum of all elements is " + Total_2DArray_Elements(brianArray));
System.out.print("\nThe average of all elements is " + Average_2DArray_Elements(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Row_Number(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Column_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Row_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Column_Number(brianArray));
}// end main method
public static void printArray(int[][] myArray)
{// begin to print arrrays
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}// end printArray method
public static int Total_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
}
}
return total;
}
public static int Average_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
int average = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
average = total / 16;
}
}
return average;
}// end method to sum array values
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[0].length; j++)
{
total += myArray[row][j];
}
}
return total;
}// end method to sum array by user input row
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[0].length; j++)
{
total += myArray[i][column];
}
}
return total;
}// end method to sum array by user input column
public static int The_Largest_Value_In_Certain_Row_Number(int[][] myArray)
{// begin method to return largest number by user input row
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the row you would like the highest value from: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
if (myArray[row][j] > highestValue)
highestValue = myArray[row][j];
}
}
return highestValue;
}// end method to return largest number by user input row
public static int The_Largest_Value_In_Certain_Column_Number(int[][] myArray)
{// begin method to return largest number by user input column
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the column you would like the highest value from: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[i].length; j++)
{
if (myArray[i][column] > highestValue)
highestValue = myArray[i][column];
}
}
return highestValue;
}// end method to return largest number by user input column
}// end class
Here is Java 8 magic, which will help u sum, average etc of any row or colum
int[][] intArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
//Sum specific column
int columnNo=0;
Integer sumOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).sum();
Double avgOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfColum);
//Sum of specific row
int rowNo=0;
Integer sumOfRow=Arrays.stream(intArray[rowNo]).sum();
Double avgOfRow=Arrays.stream(intArray[rowNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfRow);
Change your methods to the following, should do you good :
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int j = 0; j < myArray[0].length; j++) {
total += myArray[row][j];
}
return total;
}// end..
and
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++) {
total += myArray[i][column];
}
return total;
}// end m..

How to find a index from a two dimensional array

What I'm trying to do is print the largest number within a two dimensional array and it's index location. I'm able to find the largest number, but I can't seem to figure out how to print it's index location. Anyway, here's what I have so far:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
System.out.println(max);
System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of
Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later:
public static void main(String[] args) {
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int tmpI = 0;
int tmpJ = 0;
double max = arr[0][0];
// there are some changes here. in addition to the caching
for (int i = 0; i < arr.length; i++) {
int[] inner = arr[i];
// caches inner variable so that it does not have to be looked up
// as often, and it also tests based on the inner loop's length in
// case the inner loop has a different length from the outer loop.
for (int j = 0; j < inner.length; j++) {
if (inner[j] > max) {
max = inner[j];
// store the coordinates of max
tmpI = i; tmpJ = j;
}
}
}
System.out.println(max);
// convert to string before outputting:
System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")");
Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
tmpI = i; tmpJ = j;
}
}
}
Store i, j whenever you update max.
This would be if you wanted a single index into a flatten array:
public static void main (String[] args) throws java.lang.Exception
{
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int[] flattened = new int[6*3]; // based off above
int maxIndex = 0;
double max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
flattened[i + j] = arr[i][j];
if (arr[i][j] > max) {
max = arr[i][j];
maxIndex = i+j;
}
}
}
System.out.println(max);
System.out.println(flattened [maxIndex]);
}
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0];
int maxI = 0, maxJ = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
maxI = i;
maxJ = j;
}
}
}
System.out.println(max);
System.out.println(maxI + "," + maxJ);
You've got a two-dimensional array, therefore you need to know both indexes. Adding them together won't do because you lose which-is-which. How about this:
System.out.println("[" + i + "][" + j + "]");
//C++ code
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> b;
vector<int> c;
int Func(int a[][10],int n)
{
int max;
max=a[0][0];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
b.push_back(i);
c.push_back(j);
}
}
}
b.push_back(0);
c.push_back(0);
return max;
}
void display(int a[][10],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
}
int main()
{
int a[10][10],n;
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<endl;
display(a,n);
cout<<endl;
cout<<Func(a,n)<<" is the greatest "<<endl;
if(b.size()==1&&c.size()==1)
{
cout<<"Location is (1,1)"<<endl;
}
else
{
b.erase(b.end() - 1);
c.erase(c.end() - 1);
cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl;
}
return 0;
}
You're just adding the indices i and j together and then printing it to the screen. Since you're running throug the entire loop it's just going to be equal to 2*arr.length-2. What you need to do is store the values of i and j when you encounter a new max value.
For example:
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}};
int max = arr[0][0]; //dunno why you made it double when you're dealing with integers
int max_row=0;
int max_column=0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
max_row=i;
max_column=j;
}
}
System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]");
Don't sure that you implement effective algorithm, but why you just don't save indices i,j in another variables when you set max.
This is very simple.
if (arr[i][j] > max) {
max = arr[i][j];
maxX = i;
maxY = j;
}
FYI If you want look at "insertion sorting" algorithms if you want better implementation.

Categories