Concetti Chiave
- The program prompts users to input the number of rows and columns for a matrix.
- It uses `BufferedReader` to capture and parse the user's input into integers for matrix dimensions.
- A random matrix is generated with integers ranging from 0 to 9 using the `Math.random()` function.
- The program computes the transpose of the matrix, swapping rows and columns.
- Both the original matrix and its transpose are printed for the user to view.
import java.io.*;
public class Trasposta
{
public static void main(String[] args)
{
InputStreamReader input= new InputStreamReader(System.in);
BufferedReader tastiera = new BufferedReader(input);
int righe,colonne;
System.out.print("Inserire il numero di righe: ");
try
{
String numeroLetto=tastiera.readLine();
righe=Integer.valueOf(numeroLetto).intValue();
}
catch(Exception e){return;}
System.out.print("inserire il numero di colonne: ");
try
{
String numeroLetto=tastiera.readLine();
colonne=Integer.valueOf(numeroLetto).intValue();
}
catch(Exception e){return;}
int matr[][] = new int [righe][colonne];
int trasp[][] = new int [colonne][righe];
matrice(matr,righe,colonne);
trasposta(matr,trasp,righe,colonne);
}
static void matrice(int[][]matr,int righe,int colonne)
{
System.out.println("\nMatrice: ");
for(int riga=0;riga
{
for(int colonna=0;colonna
{
matr[riga][colonna]=(int)(Math.random()*10);
System.out.print(matr[riga][colonna]+" ");
}
System.out.println();
}
}
Calculation and printing of transpose
static void trasposta(int[][] matr, int[][] trasp, int righe, int colonne)
{
System.out.println("\nMatrice trasposta:");
for(int riga=0;riga
{
for(int colonna=0;colonna
{
trasp[riga][colonna] = matr[colonna][riga];
System.out.print(trasp[riga][colonna]+" ");
}
System.out.println();
}
}
}
Domande da interrogazione
- What is the primary function of the Java program provided?
- How does the program handle user input for matrix dimensions?
- What method does the program use to fill the matrix with values?
The primary function of the Java program is to generate a random matrix based on user-defined dimensions and then compute and display its transpose.
The program uses `BufferedReader` to read user input for the number of rows and columns, converting these inputs from strings to integers. If an exception occurs during input, the program exits.
The program fills the matrix with random integers between 0 and 9 using the `Math.random()` function within the `matrice` method.