import java.util.*;
public class triangle{
public static void main(String args[]){
Scanner input_Obj = new Scanner(System.in);
System.out.println("Enter the number of lines in the triangle");
int sum = 0;
int mat_size = input_Obj.nextInt(); //input of the size of the triangle
System.out.println("enter the inputs");
int input_Array[][] = new int[mat_size][mat_size];
for (int row = 0; row < mat_size; row++){
for (int col = 0; col < col; col++){
input_Array[row][col] = input_Obj.nextInt();
}
}
if (mat_size >= 3){
int[] sum_array = new int[2*(mat_size-2)];
for (int row = 1; row < mat_size; row++){
for(int col = 0;col<=row;col++){
sum += input_Array[row][col];
}
sum_array[row-1] = sum;
}
}
else if(mat_size == 2){
if (input_Array[1][0]<input_Array[1][1]){
System.out.println("minimum of the two elements in second line is:" +input_Array[1][0]);
}
else{
System.out.println("minimum of the two elements in second line is:" +input_Array[1][1]);
}
}
else{
System.out.println("minimum sum can't be calculated");
}
}
}
It is not storing values in the input array
It is taking the input in mat_size but not taking inputs into the array
I'm trying to find the minimum sum inside the triangle
for (int col = 0; col < col; col++)
col < col this is the issue as condition is never satisfied that is why it is not taking any input, change this condition to
for (int col = 0; col < mat_size; col++)
Related
I'm trying to sum of rows of Matrix
When I just put elements in 2D array output is right but when I'm trying using Scanner output result is different
SAMPLE INPUT
2
1 2
3 4
Output:
3
7
Below code result correct
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int a[][] = {
{1, 2,},
{ 3, 4}
};
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
Result incorrect if I'm trying with Scanner
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int column = sc.nextInt();
int [][] a = new int[row][column];
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
With the sample input you've provided, you shouldn't be reading the number of rows and columns, but just a single int for the number of both rows and columns:
int size = sc.nextInt();
int [][] a = new int[size][size];
for (int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
a[i][j] = sc.nextInt();
}
}
I do not see any logical problem with your code. However, it is equally important to keep your code clean and user friendly. I recommend you address the following points if you are serious about programming:
The following declaration is unnecessary:
rows = a.length;
cols = a[0].length;
You can simply use row and column instead of creating rows and cols for the same thing.
You should remove all such unnecessary things which create noise in your code.
You have missed printing the sum of each column i.e.
System.out.println(sumCol);
You do not need to declare throws IOException with main for this code.
You should always display a message describing the input; otherwise, the user remains clueless about what he/she is supposed to input.
Given below is the code incorporating these comments:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int row = sc.nextInt();
System.out.print("Enter the number of columns: ");
int column = sc.nextInt();
int[][] a = new int[row][column];
for (int i = 0; i < row; i++) {
System.out.println("Enter " + column + " integers: ");
for (int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int sumRow, sumCol;
// Calculates sum of each row of given matrix
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < column; j++) {
sumRow = sumRow + a[i][j];
}
System.out.println("Sum of row " + i + ": " + sumRow);
}
// Calculates sum of each column of given matrix
for (int i = 0; i < column; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + a[j][i];
}
System.out.println("Sum of column " + i + ": " + sumCol);
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 4
Enter 4 integers:
1 9 2 8
Enter 4 integers:
2 8 3 7
Enter 4 integers:
3 7 4 6
Sum of row 0: 20
Sum of row 1: 20
Sum of row 2: 20
Sum of column 0: 6
Sum of column 1: 24
Sum of column 2: 9
Sum of column 3: 21
I'm trying to find the total amount of odd numbers in a 2D array inputted by the user in java. I'm also trying to find the sum of all those odd numbers. I've figured out how to find the number of odd numbers in a strictly square 2d array (ie. 2x2, 3x3, 4x4, etc) but when I input an array size of for example 2x3 or say 5x6 the output is incorrect. What am I doing wrong?
import java.util.Scanner;
public class SumOfOdd
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
System.out.println("No. of rows");
int rows = input.nextInt();
System.out.println("No. of columns");
int cols = input.nextInt();
int [][] array1 = new int[rows][cols];
System.out.println("Input array elements");
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < cols; col++)
{
array1[row][col] = input.nextInt();
}
}
int count = 0;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++)
{
if(array1[i][j] % 2 == 1)
{
count++;
}
}
}
System.out.println("Odd number count = " + count);
}
}
Replace
for(int j = 0; j < array1.length; j++)
with
for(int j = 0; j < array1[i].length; j++)
Replace the nested for loop in the end
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++){
with
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
This is what I written:
import javax.swing.JOptionPane;
public class JavaTest{
public static void main(String[] args){
String numberString = JOptionPane.showInputDialog(null, "Enter number here: ",
null, JOptionPane.INFORMATION_MESSAGE);
int number = Integer.parseInt(numberString);
printMatrix(number);
}
public static void printMatrix(int n){
int[][] myList = new int[n][n];
String output = "";
for (int row = 1; row <= n; row++){
for (int col = 1; col <= n; col++){
myList[row][col] = (int) (Math.random() * 2);
}
}
for (int row = 1; row <= n; row++){
for (int col = 1; col <= n; col++){
if (col == n){
output += "\n" + myList[row][col];
}
else{
output += myList[row][col] + " ";
}
}
}
if (n < 0){
JOptionPane.showMessageDialog(null,
"Invalid input!");
}
else{
JOptionPane.showMessageDialog(null,
output);
}
}
}
I run it and enter 3 in a dialog box, and the eclipse IDE shows that
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at JavaTest.printMatrix(JavaTest.java:17)
at JavaTest.main(JavaTest.java:8)
I guess at line 17 and 8 the program goes wrong but I don't know how to improve it.
What can I do to improve my code? Thanks!
You're looping from 1 to n:
for (int row = 1; row <= n; row++){
for (int col = 1; col <= n; col++){
Indexes begin at 0, not at 1. The loops should be from 0 to n-1:
for (int row = 0; row < n; row++){
for (int col = 0; col < n; col++){
(This same error may likely be in other places than just the first line that threw the exception.)
Except for an extra column produced by the code, everything works fine except my avg method which was meant to average the value in each row. I'm new to coding, so maybe I'm not seeing the problem, but the method isn't working as intended. At first I thought it was an issue with the sum but changing it didn't really resolve the initial problem. A column input of (2,1,3) will produce an exception error at 1 but does not occur when the input is (1,3,2). Also the avg is producing only 2 regardless of column length.
I'm aiming for the code to print this when column input of (1,2,3) is entered:
A:2.0 [1.0]
B:2.0 2.0 [2.0]
C:2.0 2.0 2.0 [3.0]
where the bracketed term is the average for that row.
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 0; row < figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
public static double avg(double temp[][]) {
int sum = 0;
int avg = 0;
for (int row = 0; row < temp.length; row++){
for (int col = 0; col < temp[col].length; col++)
sum += temp[row][col];
}
avg = sum / temp.length;
return avg;
}
}
I think what you are doing wrong is instead of summing up all elements of a row and taking average, you are summing up the whole matrix and taking average which will always be the same value.
While working on a code for making a irregular 2D-array, I discovered a weird error while messing with different inputted values for the column. While the row works, the column length input returns either the wrong amount or a null pointer error occurs. I'm not sure what might be causing this since inputs such as ( 1 , 2 , 3) returns the correct table but (2 , 1, 3) will not. Also in a row of 4 with column inputs of (2, 3, 4, 5) returns "index out of bounds exception: 5" when there shouldn't be able to be out of bounds because of the while loop that should keep it with in reasonable range. Neither the main nor the display method seems to be saving the intended column length correctly and I can't seem to spot why.
It seems the array is set to 3 rows with column length of 1 , 2 , 3.
The output for row(3) and column(2,3,1) gives:
A:2.0
B:2.0 2.0
C:2.0 2.0 2.0
when I want is:
A:2.0 2.0
B:2.0 2.0 2.0
C:2.0
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
//greetings
System.out.println("");
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+(int)'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while(columns < 0 || columns >= 8) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 1; row < figures.length; ++row) {
// printing data row
group = (char)((row-1)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
//----------MENU
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");
choice = Keyboard.next();
letter = choice.charAt(0);
letter = Character.toUpperCase(letter);
if(letter == 'P') {
display(figures);
}
}
public static void display(double x[][]) {
int average, total;
char group;
System.out.println(" ");
for(int row=1;row<x.length;row++) {
group = (char)((row-1)+(int)'A');
System.out.print(group+" : ");
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+" ");
}
System.out.print("["+","+avg(x)+"]");
System.out.println();
}
}
public static int avg(double[][] temp) {
int sum = 0;
int avg = 0;
for (int col = 0; col < temp[0].length; col++) {
sum = 0;
for (int row = 0; row < temp.length; row++)
sum += temp[row][col];
System.out.println(sum);
}
avg = sum / temp.length;
return avg;
}
}
In Creating 2D Array,
Change this
double[][] figures = new double[rows + 1][num];
to
double[][] figures = new double[rows][num];
and
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
to
figures[t] = new double[columns] ;
In Printing Array
Change this
for(int row = 1; row < figures.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < figures.length; ++row) {
group = (char)((row)+(int)'A');
In display function
Change this
for(int row = 1; row < x.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < x.length; ++row) {
group = (char)((row)+(int)'A');
It's this
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
I think you meant actually
figures[t] = new double[columns];