I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.
Related
package Matrix;
import java.util.Scanner;
public class Matrix
{
public static void main(String[] args) {
System.out.print("Enter 2D array size : ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int columns=sc.nextInt();
System.out.println("Enter array elements : ");
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=sc.nextInt();
}
}
System.out.print("\n \n");
for(int []x:twoD){
for(int y:x){
System.out.print(y+" ");
}
System.out.println();
}
System.out.println("");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
}
}
}
how can I print the sum of the columns as well?
here is what I have so far
My expected output must be :
5 9 8 = 22
3 8 2 = 13
4 3 9 = 16
___________
12 20 19
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
You already have added up the elements in the row. Now to add up the columns instead of trying to change the row in your for loop change the columns to add up.
Change
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
To
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
Therefore you will have a loop that runs effectively for every column and has the sum at 0 in the beginning and at the accurate sum at the end of going through each column and all that is left is just to print it out.
If you want to have this implemented in JOption than instead of using Scanner in Java, you would have to import the JOption Library with this import statement
import javax.swing.JOptionPane;
Then you would change your input of 2D Array Size to using the method of showInputDialog. Remember that showInputDialog returns a String and so you would need to use parseInt to turn it to a Integer. Here is an example
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D Array
Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
Next change the input of the Array to also use this method. Like this
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
Resulting in the Final Code being
import javax.swing.JOptionPane;
public class Matrix{
public static void main(String[] args) {
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
System.out.print("\n \n");
for(int []x:twoD){
int cSum = 0;
for(int y:x){
System.out.print(y+" ");
cSum+=y;
}
System.out.println(" = "+cSum);
}
System.out.println("");
System.out.println("___________");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
}
}
}
Below is the code I'm messing with, pretty basic. I was looking for a way to print only specific elements of the array. For example, if I wanted to print only the element at index 1 of array[i], as well as the element at index 1 of array[j] when its value is 1. See below for the output I'm looking for.
Expected output :
1 3 5
4
7 8 9
Code:
public class multiDimensional {
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
System.out.print(arr[i][j]+" ");
//System.out.println();
}
System.out.println();
}
}
}
Actual output :
1 3 5
2 4 6
7 8 9
You can produce your expected output by using an if statement to decide when to write a value:
public static void main(String args[]){
int arr[][] = {{1,3,5}, {2,4,6}, {7,8,9}};
for(int i=0; i < 3; i++){
for(int j=0; j < 3; j++){
if (i == 0 // in the first row
|| i == 2 // in the last row
|| j == 1) { // in the middle column of the middle row
System.out.print(arr[i][j]+" ");
} else {
System.out.print(" "); // this is here to keep the spacing right
}
//System.out.println();
}
System.out.println();
}
}
Note: There are many other ways of coding this, however the approach I am showing is merely to demonstrate how the if statement works.
Please see this code:
import java.util.Scanner;
public class Array
{
public static void main(String args[])
{
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++)
{
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
Scanner scan2=new Scanner(System.in);
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextLine();
}
OUTER:
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":");
break OUTER;
}
INNER:
for (int l = 0; l < numbers.length; l++)
{
System.out.println(numbers[ l ]);
break INNER;
}
}
}
I am a newbie, learning Array as of now, in Java. I want to print the outcome of the code above as follows:
Enter 5 numbers:
//Say:
RED
GREEN
BLUE
PINK
YELLOW
Enter 5 numbers:
1
2
3
4
5
//Output of the code should be:
RED: 1
GREEN: 2
BLUE: 3
PINK: 4
YELLOW: 5
How can I print the array? I am only able to print up to "RED: 1" only, after which my program ends due to break statement.
Your last for does not a have any purpose. Just try :
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++){
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++) {
numbers[j]=scan.nextLine();
}
for (int k = 0; k < names.length; k++){
System.out.println(names[ k ] + ":"+ numbers[k]);
}
}
}
ANd it's stop at the first because you break your for
scan.nextLine() reads the whole line of input that is it reads until you don't enter \n new line charachter, so use nextInt() instead of that. Also each System.out.println() is used to print a whole line so only one loop can be used. If names and numbers have same length. And change numbers[] from String to int, that would be more type safe.
int numbers[] = new int[5];
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextInt();
}
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":" + numbers[k]);
}
Since the number of elements be it color or numericals that you're trying to get from the user is fixed here i.e 5, why complicate things? Use a single for loop to print all the contents of both the arrays:
for(int k=0;k<names.length;k++){
System.out.println(names[k] + ":"+numbers[k]);
}
I am working on an assignment in which I need to read in sample input from a file and insert it into a 2D array. Here is an example of input:
5 6
1 3 4 B 4 3
0 3 5 0 0 9
0 5 3 5 0 2
4 3 4 0 0 4
0 2 9 S 2 1
The 5 and 6 are the dimensions of the array. The user must be able to input many arrays like this one at once, the program ends when the user inputs -1. This is the code I have so far that doesn't seem to be working as it should(I print out the array to make sure the code works):
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();
sc.useDelimiter(" ");
String[][] map = new String[arHeight][arWidth];
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();
}//end inner for
}//end outter for
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}//end outter for
}
The assignment states that I cannot use recursion and that I must use 2D arrays. I have looked at other questions but still can't seem to figure it out.
Thanks for the help!!
you read the whole line i*j times
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextLine();
also you keep al the data in a string array and I don't know why. Here is the solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arHeight = sc.nextInt();
int arWidth = sc.nextInt();
int[][] map = new int[arHeight][arWidth];
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
map[i][j] = sc.nextInt();
}//end inner for
}//end outter for
for(int i=0; i<arHeight; i++){
for(int j=0; j<arWidth; j++){
System.out.print(map[i][j] + " ");
}//end inner for
}
}
Then try to use
char[][] map = new char[arHeight][arWidth];
and in the for loop:
if(sc.next().charAt(0) != " ") map[i][j] =sc.next().charAt(0);
This way you should read all the chars which are not " ".
I am trying to print pascal's triangle using 2D int array
And printing 2D array in below way
public static void pascal (int n)
{
int[][] pascalArray = new int[n][n];
// Code here
}
printArray(pascalArray);
public static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<array[i].length;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
For n =4
I am getting below output
Enter rows in the Pascal's triangle (or 0 to quit): 4
1 0 0 0
1 1 0 0
1 2 1 0
1 3 3 1
Now I want white-space instead of zero or an isosceles triangle format for pretty print
Is that possible in for 2D int array
or can we change 2D int array into some string array in printArray method and achieve the same?
I tried system.out.format but some how I am unable to get the output because of int 2D array
If you know you want a triangle, and you know the array is square, you could simply change the upper bound of the inner loop.
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<=i; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
You may just add the instruction that I added below. It prints only if the value in the array is not equal to "0". If it's a String array, use the equals() method
for (int i = 0; i < array.length; i++)
{
for(int j=0; j<array[i].length;j++)
{
if (array[i][j] != 0) System.out.print(array[i][j] + " ");
}
System.out.println();
}