I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output:
The problem is every time the maximum sum is the third row how to solve these issues.
int [][] scores = new int[4][3];
for (int i=0; i<scores.length; i++)
{
System.out.print("Enter values for row "+i+": ");
for (int j=0; j<scores[i].length;j++)
scores[i][j] = kbd.nextInt();
}
int sum, sumMax, ii=0;
for (int i=0; i<scores.length; i++)
{
sum =0; sumMax = 0; ii=0;
for (int j=0; j<scores[i].length;j++)
{
sum += scores[i][j];
if (sum>sumMax)
{
sumMax = sum;
ii = i;
}
}
}
System.out.println("Row "+ii+" has the maximum sum");
System.out.print("Row "+ii+" has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
To print a specific row, you need one loop only
System.out.print("Row " + ii + " has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
Or with Arrays.toString
System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row
int sum, sumMax = Integer.MIN_VALUE, ii = 0;
for (int i = 0; i < scores.length; i++) {
sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
if (sum > sumMax) {
sumMax = sum;
ii = i;
}
}
You can add the rows while getting the input from scanner and store them in an array. Then you can search for the max value in the sums array:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int[][] scores = new int[4][3];
int[] rowSums = new int[4];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter values for row " + i + ": ");
for (int j = 0; j < scores[i].length; j++){
scores[i][j] = kbd.nextInt();
rowSums[i] += scores[i][j];
}
}
int index = 0;
int maxSum = rowSums[index];
for(int i = 1; i < rowSums.length; i++){
if(rowSums[i] > maxSum){
maxSum = rowSums[i];
index = i;
}
}
System.out.println("Row "+index+" has the maximum sum");
System.out.print("Row "+index+" has the following values: ");
for(int i = 0; i < scores[index].length; i++){
System.out.print(scores[index][i] + " ");
}
}
}
Related
My code requests the user to input array size, as well as values. I want to sum each column and display the total below each column, as in a table.
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.println("Total column: " + columnSum);
}
You can try this
String message="Total Column:";
Scanner input=new Scanner(System.in);
int row=2,column=3;
StringBuilder array_output=new StringBuilder();
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
array_output.append(String.format("%"+message.length()+"s",""));
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
System.out.print(message+" \t");
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.print(columnSum+"\t");
}
Notice only the additional changes that added on top of your code snippet.
int a[][] = new int[row + 1][column]; // +1 for total/sum
for (int j = 0; j < column; j++){
//... rest of the logic correct
a[row][j] = columnSum;
}
//Print the result
for (int i=0; i < row+1; i++) {
for (int j=0; j < column; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
Your problem is that you are using the same variable columnSum in each interation. If you want a sum for each column then columnSum needs to be an array with an entry for each column. Then you can print that array as last output row.
I recommend to give the variables i and j a more meaningful name. Call row rows and i row and you can read you code more easily.
Just create an array of result. Now while entering data in input array, prepare your result array by adding column data in result array. In last print it. It will same time and 1 extra for loop.
int a[][] = new int[row][column];
int result[] = new int[column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
result[j] = result[j]+a[i][j];//creating array of column sum
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < result.length; j++){
System.out.print(result[j] + "\\t");
}
guys!
First of all, I'm from Brazil, so sorry if I make some grammar error.
I'm having problems to solve an exercise in whitch I have to a program that generates a matix in java with user-informed dimensions. Then, it has to fill the matrix with values which are also entered by the user. My code stops of running in my second for, passing by the columns. I get a ArrayIndexOutOfBoundException. Can you help me to see what I'm doing wrong?
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < matriz.length; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < matrix.length && j < matrix[sizes[1]].length){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (matrix[sizes[i]].length - 1);
while(i < matrix.length && j > 0){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}
Thanks in advance, guys!
Try this:
for(i = 0; i < matrix.length; i++){
matrix[i] = new int[sizes[1]];
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
Java's an object-oriented language. You'll do better if you encapsulate the behavior you need in a proper Matrix class.
I think there are a couple of errors in here, but I'll address the one you've asked about.
I believe
for(j = 0; j < matrix[sizes[0]].length; j++)
will always result in going out of bounds because you've declared:
matrix = new int[sizes[0]][sizes[1]];
Note that Java has 0 based indexing, meaning that for any array, array[array.length] will be out of bounds. This type of access is effectively what your for loop is doing.
for(j = 0; j < matrix[sizes[0]-1].length; j++)
should fix the column loop issue.
guys!
I changed some things and it worked!
Thanks for all the help!
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < sizes[0]; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < sizes[1]; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < sizes[0] && j sizes[1]){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (sizes[1] - 1);
while(i < sizes[0] && j > -1){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}
So yesterday I asked for help, and a lot of people helped me out with my question, I really appreciated that guys. However, I run into a second problem of my homework, and I have been trying to solve it from this morning, and now it's like almost 2AM in the morning, and I'm not gonna sleep until I solve this problem. I'm not going to lie, so this is my homework to test the basic knowledge of mine. I know I make major mistakes somewhere, so please help me to point them out, so I can fix them. Thank you
The output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
aver=2.5, 3.5, 4.5
This is my current code:
import java.util.Scanner;
public class Ex {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
double averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
double averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows");
int r = sc.nextInt();
System.out.println("Enter number of columns");
int c = sc.nextInt();
System.out.println("Enter values");
int[][] matrix = new int[r][c];
for (int i = 0; i < r; i++)
{
float rowSum = 0f;
for (int j = 0; j < c; j++)
{
matrix[i][j] = sc.nextInt();
rowSum += matrix[i][j];
}
System.out.println("Average of row " + i + " " + rowSum / c);
}
for (int i = 0; i < c; i++)
{
float columnSum = 0f;
for (int j = 0; j < r; j++)
{
columnSum += matrix[j][i];
}
System.out.println("Average of column " + i + " " + columnSum / r);
}
sc.close();
}
You can find the each row sum while reading the data. For column average run loop again. Hope you will sleep :)
You can print without calling other function.
import java.util.Scanner;
public class test8 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
int rowSum = 0;
int colSumArr[] = new int[columns];
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
rowSum = rowSum + array[i][j];
colSumArr[j] = colSumArr[j] + array[i][j];
System.out.print(array[i][j] + " , ");
}
System.out.println( " ave=" + (double)rowSum/columns);
rowSum = 0;
}
System.out.printf("aver=");
for(int i=0;i<columns;i++){
if(i!=columns -1)
System.out.print((double)colSumArr[i]/rows + ", ");
else
System.out.print((double)colSumArr[i]/rows);
}
}
}
This is a 2d array which is generated at random, and stores 20 integers from 100-1000. I got that part right, I'm trying to switch the rows of this 2d array and not having much luck, i tried the temp but for some reason it comes out as column array...
public static void main (String args[]){
int [][] randArray = new int[2][10];
Random rnd = new Random();
for(int i=0; i<randArray.length; i++)
for(int j=0; j<randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i=0; i < randArray.length; i++){
System.out.println("Row " + i);
for (int j=0; j < randArray[i].length; j++)
System.out.print(randArray[i][j]+ " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j=0; j < randArray[0].length; j++){
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " ");
}
}
}
Switch the rows as in row1 [1,2,3,4,5] row2 [6,7,8,9,10] to row1[6,7,8,9,10] row2[1,2,3,4,5]
You can use Arrays.deepToString(Object[]) to print the array. Display the array after you perform your swap. Something like,
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++) {
for (int j = 0; j < randArray[i].length; j++) {
randArray[i][j] = 100 + rnd.nextInt(900);
}
}
System.out.println(Arrays.deepToString(randArray));
System.out.println("Switch row ");
for (int j = 0; j < randArray[0].length; j++) {
int temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
}
System.out.println(Arrays.deepToString(randArray));
Your code is working actually I fixed only the compile error;
public static void main(String args[]) {
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++)
for (int j = 0; j < randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j = 0; j < randArray[0].length; j++) {
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " "); no i variable
}
//I added only below lines to print your result
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
}
Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.