Need to print the max element column in java - java

Hello I am new in java and I want to write a program where I will print the max element from the column in 2D table. I am updating a picture to show what actually I want to print.
Here is the code:
import java.util.*;
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
int[][] table = new int [col][row];
int max= 0;
for(int i=0; i<col; i++){
for(int j=0; j<row; j++){
max= table[i][0];
table[i][j]= sc.nextInt();
if(max<table[i][j]){
max= table[i][j];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
}
}

You can index a matrix (2D table) like this:
matrix[row][column]
where row and column are 0-based indexes.
You have to change the loop like this:
int max= 0;
for(int i=0; i<col; i++){
// select first element of a column as temp max
max= table[0][i];
for(int j=0; j<row; j++){
// cycle on rows
if(max<table[j][i]){
max= table[j][i];
}
}
System.out.println("Maximum number is "+ max);
System.out.println();
}
You have to cycle on column. Select the first element of a column as temporary maximum
You have to init the max when you end a row, not inside the nested loop
Side note: I suggest you to keep the code clean (because is a simple example and I assume you have a little file) and separate tasks:
First, read the file (perhaps print the file content to be sure the content it's ok)
Then, check the maximum of each column
In this way will be simpler for you to catch problems.

You need to separate the values insertion and finding the maximum value so you can iterate the array by columns
public class MaxColumnElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
table[i][j] = sc.nextInt();
}
}
int[][] table = new int[col][row];
for (int i = 0; i < col; i++) {
int max = table[0][i];
for (int j = 0; j < row; j++) {
if (max < table[j][i]) {
max = table[j][i];
}
}
System.out.println("Maximum number is " + max);
System.out.println();
}
}
}
Output
Maximum number is 10
Maximum number is 5
Maximum number is -3
Maximum number is 9

Related

2D Array to take float inputs from user and calculate sum of columns

I'm really new to Java and have been given a task to create a two dimensional array that takes input from the user. The problem I am having is that it needs to take in some decimal numbers as well as whole numbers then calculate the sum of each column and my program is returning an error once a decimal number is input. I have tried changing all instances of "int" to "float" but still the same error pops up. I also then need to print out the totals of each column.
My code so far is:
package sumElements;
import java.util.Scanner;
public class sumElements{
public static void main(String args[]){
int row, col, i, j;
int arr[][] = new int[3][4];
Scanner scan = new Scanner(System.in);
// enter row and column for array.
row = 3;
col = 4;
// enter array elements.
System.out.println("Enter " +(row*col)+ " array elements row by row (4 per row) : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
}
}
Changed code:
package sumElements;
import java.util.Scanner;
public class sumElements{
public static void main(String args[]){
float row, col, i, j;
float arr[][] = new float[3][4];
Scanner scan = new Scanner(System.in);
// enter row and column for array.
row = 3;
col = 4;
// enter array elements.
System.out.println("Enter " +(row*col)+ " array elements row by row (4 per row) : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextFloat();
}
}
// the 2D array is here.
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
}
}
package sumElements;
import java.util.Scanner;
public class sumElements{
public static void main(String args[]){
int row, col, i, j;
float arr[][] = new float[3][4];
Scanner scan = new Scanner(System.in);
// enter row and column for array.
row = 3;
col = 4;
// enter array elements.
System.out.println("Enter " +(row*col)+ " array elements row by row (4 per row) : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextFloat();
}
}
// the 2D array is here.
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
}
Indices must be int since elements of the array float

Trying to get the average for each element in a two dimensional array

I have a program where i have to find the average for each student score from a text file and display it as a 2D array.
I am stuck - all I accomplish every time is getting the average for each row or column, but i have to find the average for each value in the text file.
For example: 76 / 48 = 1.5 (rounding off to 1 decimal)
Here my code:
public void studentAverage(double average) throws
FileNotFoundException
{
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
//Im stucked here
rowNum += arr[row][col];
}
average = rowNum / arr[row].length;
System.out.println("StudentAverage is: "+average);
rowNum = 0;
}
}
The average for each value in the entire grid is just a single number (I think). So, all you need to is to take the running sum and then divide by the number of cells:
double sum = 0.0d;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
}
int size = arr.length*arr[0].length;
double average = sum / size;
System.out.println("StudentAverage is: " + average);
In my calculation of the size, which is the total number of students, I am assuming that your 2D array is not jagged. That is, I assume that each row has the same number of columns' worth of data.
You could use streams for this.
To get the overall average
double average = Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.average();
And to get the average per row:
double[] averagePerRow = Ararys.stream(arr)
.map(Arrays::stream)
.mapToDouble(IntStream::average)
.toArray();
This works for any 2D int array, jagged or not.
I would use List for this
public void studentAverage() throws FileNotFoundException {
File infile= new File("qdata.txt");
Scanner sc = new Scanner(infile);
double rowNum = 0;
List<List<Integer>> grades = new ArrayList<>();
double totalCount = 0.0;
while (sc.hasNext()) {
List<Integer> row = new ArrayList<>();
Scanner lineScanner= new Scanner(sc.nextLine());
while (lineScanner.hasNextInt()) {
row.add(lineScanner.nextInt());
}
grades.add(row);
totalCount += row.size();
}
int index = 0;
for (List<Integer> list : grades) {
for (Integer grade : list) {
System.out.println("Student average is " + (double)Math.round(grade.doubleValue() / totalCount * 10) / 10);
}
}
}
Check this Link - How to find average of elements in 2d array JAVA?
public class AverageElements {
private static double[][] array;
public static void main (String[] args){
// Initialize array
initializeArray();
// Calculate average
System.out.println(getAverage());
}
private static void initializeArray(){
array = new double[5][2];
array[0][0]=1.1;
array[0][1]=12.3;
array[1][0]=3.4;
array[1][1]=5.8;
array[2][0]=9.8;
array[2][1]=5.7;
array[3][0]=4.6;
array[3][1]=7.45698;
array[4][0]=1.22;
array[4][1]=3.1478;
}
private static double getAverage(){
int counter=0;
double sum = 0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
sum = sum+array[i][j];
counter++;
}
}
return sum / counter;
}
}
double sum=0;
int size=0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
size+=arr[row].length;
}
double average = sum/size;
System.out.println("StudentAverage is: "+average);

How to Create Method for Finding Largest Element in Array

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!
/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929
Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}

Adding values on 2d array java

I have created a program that lets the user input the number of rows and columns they want in a 2d array and then it fills the array with all even numbers starting from 0.
I have to add all the numbers in the array to get a total sum and I have no idea how to do that. The rest of my program is complete I'm just having trouble with the sum.
Here is my code:
import java.util.*;
public class ArrayOver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many rows? ");
int x = scan.nextInt();
System.out.println("How many columns? ");
int y = scan.nextInt();
int[][] nums = new int[x][y];
fillArray(nums);
displayArray(nums);
System.out.println();
}
public static void fillArray(int nums[][]) {
int count = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length ; col++) {
nums[row][col] = count;
count++;
count++;
}
}
}
public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {
System.out.println(Arrays.toString(nums[row]));
}
}
}
Try this:
public static void countArray(int[][] nums)
{
int total=0;
for (int row=0;row<nums.length;row++)
for (int col=0;col<nums[0].length;col++)
total += nums[row][col];
System.out.println(total);
}
This should go through all the numbers in the array and add their values to total.
If you want sum all elements of array, just do it:
int sum = 0;
for(int row = 0; row < nums.length ; row++) {
for (int col = 0; col < nums[row].length ; col++) {
sum = sum + nums[row][col];
}
}

Two Dimensional Matrix as Input

how to write two dimensional matrix as input and identifies the number with maximum number of occurrences in the matrix.
Example Input :
2 // no of rows
3 // no of columns
1 2 3 2 3 3 // here the matrix taken as input is 2 x 3 matrix. Remaining six numbers are values for the particular matrix. (elements in the first row are 1 2 3 and elements in the second row are 2 3 3)
Example output : 3
import java.util.*;
class ArrayOccurence
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
sc.nextLine();
int column = sc.nextInt();
sc.nextLine();
int element = 0;
int occurence = 0;
int arr[][] = new int[row][column]; // size of the array
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
arr[i][j] = sc.nextInt();
}
//Do not modify the code above
/* Enter your code here */
// Do not modify code below
System.out.println("Matrix element "+element+" occurs "+occurence+" times in the matrix");
}
}
Substitute your line which says Enter your code here with the following:
ArrayList<Integer> a = new ArrayList<Integer>();
int oc = 0;
int number = 0;
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++){
if(a.isEmpty()){
a.add(arr[i][j]);
}
else if(a.contains(arr[i][j])){
int temp=0;
for(int k=0; k<a.size(); k++){
if(a.get(k) == arr[i][j]){
temp++;
}
}
if(temp > oc){
number = arr[i][j];
oc = temp;
}
a.add(arr[i][j]);
}
else{
a.add(arr[i][j]);
}
}
}
Hope this helps.
You could use the double for loop again to count the occurence of each numbers:
for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
//count occurences with a HashMap<Integer,Integer> or something like that
}
Loop into your HashMap to find the one with most occurence..

Categories

Resources