I have this text file:
2
2
12
13
23
24
49
59
69
79
the first two numbers should be the rows and columns of the matrix, which is 2x2 in this case. My issue that I'm trying to get around is finding a way to include a second 2D array that holds the second matrix.
my code:
Scanner fileInput = new Scanner(new File("input1.txt"));
int n1 = fileInput.nextInt();
int n2 = fileInput.nextInt();
System.out.print("matrix is " + n1 + "x" + n2 +"\n");
int [][] firstMatrix = new int [n1][n2];
int [][] secondMatrix = new int [n1][n2];
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
firstMatrix[i][j] = fileInput.nextInt();
}
}
}
System.out.println("Matrices: ");
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.println(firstMatrix[i][j]);
}
}
it only prints the following:
12
13
23
24
How do I make it read the next four lines of integers from the file? It would also be helpful to understand how I can make it look something like this:
12 13
23 24
EDIT: This approach seemed to help with the last question:
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
{
System.out.print(firstMatrix[i][j] + " " );
//System.out.print(secondMatrix[i][j] + " ");
}
System.out.println();
}
The only problem I'm facing now is being able to include the four other integers and turn them into a matrix.
You can group them to 1 array:
int matrixNumb = 2; // number of matrix
int [][][] matrix = new int [matrixNumb][n1][n2];
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
matrix [h][i][j] = fileInput.nextInt(); // read from file
}
}
}
}
System.out.println("Matrices: ");
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.print(matrix[h][i][j]);
System.out.print("\t"); //How do you want to separate columns?
}
System.out.print("\r\n"); //How do you want to separate rows?
}
System.out.println(); //How do u want to print next matrix?
}
I have not compiled or run it, but hope it help.
You can just read data for the two arrays from file sequentially, like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
private static void readMatrix(final Scanner scanner, final int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
}
}
}
}
private static void displayMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(final String... args) throws FileNotFoundException {
final Scanner scanner = new Scanner(new File("input.txt"));
final int n1 = scanner.nextInt();
final int n2 = scanner.nextInt();
System.out.print(String.format("The matrix is %d x %d \n", n1, n2));
final int[][] firstMatrix = new int[n1][n2];
final int[][] secondMatrix = new int[n1][n2];
System.out.println("Reading data to first matrix");
readMatrix(scanner, firstMatrix);
System.out.println("Reading data to second matrix");
readMatrix(scanner, secondMatrix);
System.out.println("First Matrix");
displayMatrix(firstMatrix);
System.out.println("Second Matrix");
displayMatrix(secondMatrix);
}
}
for(int i = 0; i < n1*n1; i++)
{
for(int j = 0; j < n2*n2; j++)
{
if(fileInput.hasNextInt())
{
if(i < n1){
firstMatrix[i][j] = fileInput.nextInt();
}
else
{
secondMatrix[i][j] = fileInput.nextInt();
}
}
}
}
You have two matrix of size n*n so you can do like this:
Related
I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}
The requirement is to sort the rows of a two-dimensional array. I feel like my code is very close to being done, but I can't figure out why it isn't displaying the sorted array. I forgot to mention that we are not allowed to use the premade sorting methods. The problem is most likely in the sortRows method. Anyways, here's my code:
public class RowSorting
{
public static void main(String[] args)
{
double[][] numbers = new double[3][3];
double[][] number = new double[3][3];
int run = 0;
String answer = "";
while (run == 0)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-by-3 matrix row by row: ");
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
numbers[row][column] = input.nextDouble();
}
}
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
System.out.print(numbers[row][column] + " ");
}
System.out.print("\n");
}
System.out.println("The sorted array is: \n");
number = sortRows(numbers);
for(int row = 0; row < number.length; row++)
{
for(int column = 0; column < number[row].length; column++)
{
System.out.print(number[row][column] + " ");
}
System.out.print("\n");
}
System.out.print("\nWould you like to continue the program (y for yes or anything else exits): ");
answer = input.next();
if(answer.equals("y"))
{
continue;
}
else
break;
}
}
public static double[][] sortRows(double[][] m)
{
for(int j = 0; j < m[j].length - 1; j++)
{
for(int i = 0; i < m.length; i++)
{
double currentMin = m[j][i];
int currentMinIndex = i;
for(int k = i + 1; k < m[j].length; k++)
{
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
}
if(currentMinIndex != i)
{
m[currentMinIndex][j] = m[j][i];
m[j][i] = currentMin;
}
}
}
return m;
}
}
It looks like this block:
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
Will never happen. Because you just assigned currentMin to m[j][i] two lines before it. I believe you want to use k in that if check. Something like
if (currentMin > m[j][k]){
currentMin = m[j][k];
currentMinIndex = k;
}
As cited per ergonaut, you have a problem with the codeblock
if(currentMin > m[j][i]) ...
and also
m[currentMinIndex][j] = m[j][i];
However, you also have a problem with your for-loops.
for(int j = 0; j < m[j].length - 1; j++) ...
for(int i = 0; i < m.length; i++) ...
Both of these are oddly structured. You probably want to swap these for-loops so that you don't throw index exceptions. This will also cause you address the indices in your code. And modify your j-index for-loop to include the entire range.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet
Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}