N * N matrix by Java - java

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.)

Related

Logical error while inserting elements in to Two dimensional array using Scanner

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

Is there a way to fix my two dimensional array problem

How can I find the total sum for each two dimensional array row? I'm completely stuck...
public static void main(String[] args) {
int [][] grid = new int [10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*99);
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.println();
}
}
My current output is:
How can I show the total sum for each row in the end of the row and show column numbers
For the sum of a row, this should do. In a similar way within the i loop, if you need to count the column as well;
for(int i = 0; i < 10; i++) {
int jSum = 0;
for(int j = 0; j < 10; j++) {
jSum += grid[i][j];
System.out.print("1.");
System.out.printf("%5d ", grid[i][j]);
}
System.out.printf(" %5d", jSum);
System.out.println();
}
On the column numbering:
Either you just pust put a static print in the beginning (like print "1 2 3 4..."), or you put the following with the j loop:
if (i == 0) System.out.printf("%5d ", j); // only prints in first loop / row - print 1,2,3,4,5....

trying to store given inputs as a floyd triangle

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++)

how to randomly split the data in a two dimensional array and display them in a 75% and 25% format

I loaded a two dimensional array from a txt file. I need the program to randomly display 75% and 25% of the array separately. I tried using Math.random but it change the numbers to display from 0 to 1. I will be using the numbers in further calculations. I have enclosed the whole code. The dataSplit method is where I separate the array. The txt file that I am using in this example is for testing purposes only. I actually have a much larger file.
Thank you in advance for your help,
Avi
p.s. I am starting the column count from 1 because column 1 is to be ignored.
This is the txt file
1 6 7 8
2 9 10 11
3 12 13 14
Below is the code
package tester;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader("one.txt"));
float [][] glassdata = new float[3][4];
loadArray(glassdata, inFile);
displayArray(glassdata);
System.out.println("\n***************\n");
normalizingVector(glassdata);
System.out.println("\n***************\n");
dataSplit(glassdata);
}
public static void loadArray(float [][] g, Scanner inFile)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 0; col < g[row].length; col++)
{
g[row][col] = inFile.nextFloat();
}
}
}
public static void displayArray(float [][] g)
{
for(int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
}
public static void normalizingVector(float [][] g)
{
float temp1 = 0;
float temp2 = 0;
for (int row = 0; row < g.length; row++)
{
for(int col = 1; col < g[row].length; col++)
{
while(col < g[row].length)
{
temp1 = temp1 + (float) Math.pow(g[row][col], 2);
col++;
}
col = 1;
temp1 = (float) Math.sqrt(temp1);
while(col < g[row].length)
{
temp2 = (g[row][col]) / temp1;
System.out.print(temp2 + " ");
col++;
}
}
System.out.println();
temp1 = 0;
temp2 = 0;
}
}
public static void dataSplit(float [][] g)
{
int row;
int col;
for(row = 0; row < g.length; row++)
{
for(col = 1; col < g[row].length * 0.75; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
System.out.println("*******!##$$*************");
for(row = 0; row < g.length; row++)
{
for(col = 2; col < g[row].length * 0.25; col++)
{
System.out.print(g[row][col] + " ");
}
System.out.println();
}
}
}

Inputs for column length is returning unintended length

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];

Categories