I am supposed to create a matrix and split it into 3 methods, where first one will read matrix, second will print matrix and third one will swap diagonals. Read matrix works but I've tried to pass the parameters to other methods so they can work too but when I call them in main class, it doesn't work.
public static void readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
}
public int[][] printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
return matrix;
}
public int[][] swapDiagonals(int ColumnsAndRows, int matrix[][]) {
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
return matrix;
You can use an int[][] store the matrix returned from readMatrix.
It is redundant here to let printMatrix and swapDiagonals return int[][].
You can let printMatrix and swapDiagonals be static, so you can call them in main method.
Here is a sample:
public class Matrix {
public static int[][] readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
return matrix;
}
public static void printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void swapDiagonals(int matrix[][]) {
int ColumnsAndRows = matrix.length;
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
}
public static void main(String[] args) {
int[][] matrix = readMatrix();
printMatrix(matrix);
System.out.println("swapDiagonals:");
swapDiagonals(matrix);
}
}
Result:
Please insert how many rows and columns you want for matrix
4
12 10 14 5
14 8 9 13
2 15 5 16
11 9 8 10
swapDiagonals:
5 10 14 12
14 9 8 13
2 5 15 16
10 9 8 11
Related
If I have a partially filled 2D matrix from user input, how can I fill it in some other void method to get spiral matrix:
Here is my code: However, when I run it the dimensions of matrix still remain 1000X1000. How can I fix this problem? I need to have only two methods - fillSpiral and main. The program should get any square matrix from user then change its values in a way it becomes a spiral matrix.
import java.util.Scanner;
public class Spiral {
public static void fillSpiral(int matrix[][]) {
int row1 = 0, row2 = matrix.length, col1 = 0, col2 = matrix[0].length;
int num = 1;
while (num <= matrix.length) {
for (int col = col2-1; col >= col1; col--){
matrix[row2-1][col] = num;
num++;
}
for (int row = row2-2; row >= row1; row--) {
matrix[row][col1] = num;
num++;
}
for (int col = col1+1; col < col2; col++) {
matrix[row1][col] = num;
num++;
}
for (int row = row1+1; row < row2-1; row++) {
matrix[row][col2-1] = num;
num++;
}
row1++;
row2--;
col1++;
col2--;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
public static void main(String args[]) {
int n = 0;
int[][] matrixOutput = new int[1000][1000];
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<matrixOutput.length; i++) {
for (int j=0; j<matrixOutput[0].length; j++){
while (keyboard.hasNextInt()) {
matrixOutput[i][j] = keyboard.nextInt();
n++;
}
}
}
fillSpiral(matrixOutput);
}
}
example
Input
1 2 3
4 5 6
7 8 9
Output
5 6 7
4 9 8
3 2 1
Since the algorithm for an spiral matrix is not new i assume your only problem is to read a matrix of an fixed size. Then addressing only your main method use this
//i preferr buffered reader over scanner
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)))
{
ArrayList<String> rows=new ArrayList();
String line=null;
do
{
//example 1,2,3,4,5
System.out.println("Enter an row for this matrix all elements , seperated or an empty string to end input");
line=reader.readLine().trim();
if(!(line.isEmpty() || line.isBlank())){rows.add(line);}
else{line=null;}
}
while(line!=null);
//i assume a square matrix so rows=columns
int n=rows.size();
int[][] matrix=new int[n][n];
for(int i=0;i<n;i++)
{
//split at comma to get columns
String[] columns=rows.get(i).split(",");
//assign each column to the ith row
for(int j=0;j<n;j++){matrix[i][j]=Integer.parseInt(columns[j]);}
}
fillSpiral(matrix);
}
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 need to make a multiplication table that shows 1 * 1 up to 12 * 12. I have this working but it needs to be in 13 columns in a format that looks like the diagram below, really appreciate any help.
1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 ...
2 2 4 6 8 10 ....
3
4
5
6
...
Code so far:
public class timetable {
public static void main(String[] args) {
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
}
}
Print column headings before printing the table, and print row headings at the start of each row. You can use the code below.
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.printf("%6s", "");
for (int col = 0; col < table[0].length; col++) {
System.out.printf("%6d", col+1);
}
System.out.println();
for (int row = 0; row < table.length; row++) {
// Print row headings
System.out.printf("%6d", row+1);
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
This only prints 9x9 timetable, if you need to change it 12x12, then just change the numbers in the code from "9" to "12", and add more "----" lines in the system output to match it
This includes " * |" and "----" ...
Thought this might be helpful for anyone else
Output:
9x9 Timetable
public class timetable2DArray
{
public static void main(String[] args)
{
int[][] table = new int[9][9];
for (int row=0; row<9; row++)
{
for (int col=0; col<9; col++)
{
table[row][col] = (row+1) * (col+1);
}
}
// Print column headings
System.out.print(" * |");
for (int col = 0; col < table[0].length; col++)
{
System.out.printf("%4d", col+1);
}
System.out.println("");
System.out.println("------------------------------------------");
for (int row = 0; row < table.length; row++)
{
// Print row headings
System.out.printf("%4d |", row+1);
for (int col = 0; col < table[row].length; col++)
{
System.out.printf("%4d", table[row][col]);
}
System.out.println();
}
}
}
int [][] A = new int[5][5];
int [][] B = new int[5][5];
for (int row = 0; row < A.length; row++) {
System.out.println();
for (int col = 0; col < A.length; col++) {
B[row][col] = (row+1)*(col+1);
System.out.print("\t");
System.out.printf("%2d", B[row][col]);
}
}
You could implement a timesTable() method. Here's my code, modify it anyway you would like.
//main driver
public static void main(String[] args) {
int[][] data; //declaration
data = timesTable(4,6); //initialisation
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
//method
public static int[][] timesTable(int r, int c)
{
int [][] arr = new int[r][c];
for (int row = 0; row < arr.length ; row++)
{
for (int column = 0; column < arr[row].length; column++)
{
arr[row][column] = (row+1)*(column+1);
}
}
return arr;
}
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();
}
}
}
I'm not sure why my code will not work. Help please! :D
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 1; row <= yes.length ; row++)
{
for (int column = 1; column <= yes[row].length; column++)
{
yes[row][column] = (row)*(column);
}
}
return yes;
The index of Array should start 0 rather 1.
Change to the following code and have a try.
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 0; row < yes.length ; row++)
{
for (int column = 0; column < yes[row].length; column++)
{
yes[row][column] = (row+1)*(column+1); }
}
return yes;
}
Test code and output in console is as follows:
public class Test1 {
public static void main(String[] args) {
int[][] data = new int[5][5];
data = timesTable(5,5);
for (int row = 0; row < data.length ; row++)
{
for (int column = 0; column < data[row].length; column++)
{
System.out.printf("%2d ",data[row][column]);
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 0; row < yes.length ; row++)
{
for (int column = 0; column < yes[row].length; column++)
{
yes[row][column] = (row+1)*(column+1);
}
}
return yes;
}
}
Output in Console:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
If you're getting ArrayIndexOutOfBounds its because you are starting from index 1, when it should be 0.
This should do the job:
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[r][c];
for (int row = 1; row <= yes.length ; row++)
{
for (int column = 1; column <= yes[row].length; column++)
{
yes[row-1][column-1] = (row)*(column);
}
}
return yes;
}
int a[][]={{2,3},{3,4}};
int b[][]={{2,3},{3,4}};
int c[][]=new int[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j]=a[i][j]*b[i][j];
System.out.print(c[i][j]+"\t");
}
System.out.println();
}