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);
}
Related
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] + " ");
}
}
}
How to flip this triangle?
So i was making aritmethic sequance triangle. It was upside down.
How do I turn it 180 degree?
for example:
1=1
1+2=3
1+2+3=6
etc...
my code:
package javaapplication4;
public class NewClass5 {
public static void main(String[] args) {
int i=5,a;
for(int j=i; j>=1; j--) {
for(a=1; a<=i; a++)
System.out.print(a +" + ");
int n = 0;
for(a = 1; a<=i; a++) {
n = n + a;
}
System.out.print(" = "+ n);
System.out.println();
i--;
}
}
}
You can do it for any n, by getting input from the user
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int add = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
add += j;
}
System.out.println(add);
}
I think you just need to change the sequence of loop from descending to ascending, rest of the things should be the same:
for (int i = 1; i <= 5; i++) {
int sum = 0;
for (int j = 1; j <= i; j++) {
System.out.print(j);
if (j == i)
System.out.print("=");
else
System.out.print("+");
sum += j;
}
System.out.println(sum);
}
When I run this, I'm able to see expected output:
src : $ java NewClass5
1=1
1+2=3
1+2+3=6
1+2+3+4=10
1+2+3+4+5=15
I am trying to find length of an array formed by union of two arrays. I can print out the union elements like this, but have no idea how to get length of my union array. Any ideas?
Can it be count variable length of my union array?
int[] array1={1,3,2,5};
int[] array2={4,5,1,3,2};
int m = array1.length, n = array2.length, k = array1.length, i = 0, flag = 0;
int c[] = new int[m + n];
int d[] = new int[m];
for (i = 0; i < m; i++) {
c[i] = array1[i];
}
for (i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (array2[i] != array1[j]) {
flag = 1;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
c[k] = array2[i];
k++;
}
}
int count = 1;
for (i = 0; i < k - 1; i++) {
count++;
}
int p = 0;
for (i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (array2[i] == array1[j]) {
flag = 1;
break;
} else {
flag = 0;
}
}
if (flag == 1) {
d[p] = array2[i];
p++;
}
}
System.out.println("The length of the union array is: " + count);
The count should be k + m and not k. So just replace:
for (i = 0; i < k - 1; i++)
with
for (i = 0; i < k + m - 1; i++)
Better solution would be to assign k + m to count and print it. Something like this:
count = k + m;
System.out.println("count is " + count);
If you want a unique count then use Set:
Set<Integer> set = new HashSet<>();
set.addAll(Arrays.asList(array1));
set.addAll(Arrays.asList(array2));
count = set.size();
Here is the link for definition of the hourglass problem:
https://www.hackerrank.com/challenges/30-2d-arrays
I wrote the following program:
package day11;
import java.util.Scanner;
public class Solution {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int[][] arr = new int[6][6];
int maxHourGlassValue = 0;
int temp = 0;
int currMax = 0;
int k = 0, l = 0;
for(int i = 0 ; i < 6 ; i++){
for(int j = 0 ; j < 6 ; j++){
arr[i][j] = scan.nextInt();
}
}
for(int i = 1 ; i < 5 ; i++){
for(int j = 1 ; j < 5 ; j++){
if(maxHourGlassValue < currMax){
maxHourGlassValue = currMax;
}
}
}
System.out.println(maxHourGlassValue);
}
}
I could only run 6 out of 8 given test cases. What could possibly go wrong ????
Try this code, i did not write that code, i just copy it and modified it from here
import java.util.Scanner;
public class Test {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int size = 6;
int[][] m = new int[size][size];
//numbers input
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
m[i][j] = scan.nextInt();
}
}
int temp = 0, MaxSum = -99999;
for (int i=0; i<size; ++i) {
for (int j=0; j<size; ++j) {
if (j+2 < size && i+2 < size) {
temp = m[i][j] + m[i][j+1] + m[i][j+2] + m[i+1][j+1] + m[i+2][j] + m[i+2][j+1] + m[i+2][j+2];
if (temp >= MaxSum) {
MaxSum = temp;
}
}
}
}
System.out.println(MaxSum);
}
}
Below is the code which will run successfully for all the test cases of hourglass problem.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int[][] arr = new int[6][6];
int maxHourGlassValue = -63;//Assigning (-9*7=)-63 which is the minimum possible value of "hourglass sum".
//Reading inputs.
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
arr[i][j] = scan.nextInt();
}
}
//Logic.
/**
* Index of both i and j will run from 1 to 4 (one less than n-1 where n = 6)
* So for each i and j iteration calculating the sum of hourglass.
*/
int iHGValueTemp = 0;
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
iHGValueTemp = arr[i][j] + /*Main element*/
arr[i - 1][j - 1] + arr[i - 1][j] + arr[i - 1][j + 1]+ /*Top three elements of main element.*/
arr[i + 1][j - 1] + arr[i + 1][j] + arr[i + 1][j + 1]; /*Bottom three elements of main element.*/
if (iHGValueTemp > maxHourGlassValue) {
maxHourGlassValue = iHGValueTemp;
}
}
}
//Output.
System.out.println(maxHourGlassValue);
}
}
I have written description within code in the comments only. Please refer to that and discuss with me if any doubt.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet