Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.
import java.util.Scanner;
public class multiplication {
static int a,b;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
a =input.nextInt();
b = input.nextInt();
int[][] matrix = new int[a][b];
matrix = timesTable(a,b);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(" "+matrix[row][column] + "\t|");
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[c][c];
for ( r = 0; r < yes.length ; r++)
{
for (c = 0; c < yes[r].length; c++)
{
yes[r][c] = (r+1)*(c+1);
}
}
return yes;
}
}
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
//print
}
This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?
Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.
Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.
Related
I'm trying to figure out how to turn this type of input from scanner:
3
a b c
d e f
g h i
into this array:
String[][] arr = {{a,b,c}, {d,e,f}, {g,h i}}
The first row specifies the dimensions of the array, and the lines after are the matrix.
This is the code that I have so far:
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
scan.nextLine();
String[][] matrix = new String[num][num];
I know I'll probably need a loop that separates each entry in the row by spaces and then add it into the first row in the array, then check for a new line repeat with each row, but I can't figure out how to implement this code.
I've made the program in Python, but I can't figure out how to do this in Java.
The below code answers your question, namely processes the input as indicated in your question which is first obtaining the [square] matrix dimension followed by separate lines where each line contains all the elements for a single row of the matrix where the elements are separated by spaces.
import java.util.Arrays;
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Number of elements in each row and each column of matrix.
int num = scan.nextInt();
String[][] matrix = new String[num][num];
scan.nextLine(); // Ignore return value.
for (int row = 0; row < num; row++) {
// Enter elements for single row of matrix, delimited by spaces.
String line = scan.nextLine();
String[] elements = line.split("\\s+");
for (int column = 0; column < num; column++) {
matrix[row][column] = elements[column]; // Note: user entered values not checked.
}
}
System.out.println(Arrays.deepToString(matrix));
}
}
Output for a sample run of the above code, using the sample values from your question:
3
a b c
d e f
g h i
[[a, b, c], [d, e, f], [g, h, i]]
Firstly, since we are taking int rather than strings, the matrix 2d-array should be one of int.
The rest should be almost identical structurally to your python code as far as I can imagine:
...
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int[][] matrix = new int[num][num];
scan.nextLine();
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
matrix[i][j] = scan.nextInt();
}
scan.nextLine();
}
...
You can solve this problem by looping through the rows and columns in a 2D array.
import java.util.*;
class Test {
public static void main(String[] args) {
int row = 3, column = 3;
String[][] matrix = new String[row][column];
read(matrix, row, column);
print(matrix, row, column);
}
public static void read(String[][] matrix, int row, int column) {
Scanner scanner = new Scanner(System.in);
String input;
for(int i = 0 ; i < row ; ++i) {
for(int j = 0 ; j < column ; ++j) {
input = scanner.nextLine();
matrix[i][j] = input;
}
}
}
public static void print(String[][] matrix, int row, int column) {
for(int i = 0 ; i < row; ++i) {
for(int j = 0 ; j < column ; ++j) {
String result = String.format("MATRIX [%d][%d]: %s", i, j, matrix[i][j]);
System.out.println(result);
}
}
}
}
My goal for this program is to create a 2D-array ratings whose size is specified by the first two arguments from the command line. args[0] would represent the number of rows r and arg[1] would represent the number of columns c. The next arguments that follow would all be used to fill in the array. So if the command-line argument was 3 2 5 2 3 3 4 1. I would hope that the array would be 3 rows by 2 columns. The value 5 would be in ratings[0][0], the value 2 would be in ratings[0][1], the value 3 would be in ratings[1][0], etc. After that, I want to compute the sum of each column. So column 0 would be 12 and column 1 would be 6 in this scenario.
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
int c = Integer.parseInt(args[1]);
int[][] ratings = new int[r][c];
int z = 2;
int y = 3;
int x = 0;
int counting = 0;
int sum = 0;
for (int rows = 0; rows < ratings.length; rows++ ) {
for (int column = 0; column < ratings[c].length; column++){
ratings[rows][column] = Integer.parseInt(args[z]);
sum += ratings[rows][column];
z++;
}
System.out.println(sum);
sum = 0;
}
//System.out.println(movieRating);
}
This is my attempt at summing the columns but this right now just sums 5 and 2, 3 and 3, 4 and 1. I want the columns not the rows to be summed but do not know how to fix it. Thank you
You seem to be adding the values to the 2D array correctly. What you're missing is an additional nested loop to print out the column totals:
for (int i = 0; i < ratings[c].length; i++) {
int colSum = 0;
for (int j = 0; j < ratings.length; j++) {
colSum += ratings[j][i];
}
System.out.println(colSum);
}
Add that where you currently have that //System.out.println(movieRating); line. Since you were adding the numbers to the array row-wise, you need to flip the for loops to be able to sum the columns.
Things you did right
You correctly initialized the ratings 2D-array with the values given on the command line. Let me re-write this below without your attempt at computing the columns' sum. Note that I renamed the variables so that the indices used in the for loop are single letter variable.
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
argIndex++;
}
}
}
Thing you didn't get right
The ratings array is filled row by row. In the code you posted, you compute in variable sum the sum of the elements inserted in the same row. This is the reason why it doesn't print the results you expected.
To compute the sum of each columns, I would recommend you create a new array in which to store this result. Integrating it with the code above:
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int[] columnSums = new int[columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
columnSums[c] += ratings[r][c];
argIndex++;
}
}
// array columnSums contains your results
}
I have changed your original code with a simpler version.
Let me know if you have problems understanding the solution.
public static void main(String[] args)
{
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int arrayLength = row * col; // use a single dimension array, for simplicity
int[] ratings = new int[arrayLength]; // the array size is based on the rows and columns
// add data to the 'ratings' array
// This is not actually needed because the conversion can be done directly when the columns are summed up
for(int i = 0; i < arrayLength; i++)
{
ratings[i] = Integer.parseInt(args[i + 2]);
}
// sum up the columns using the % operator
int[] result = new int[col];
for(int i = 0; i < arrayLength; i++)
{
result[i % col] += ratings[i];
}
// print result
for(int i = 0; i < result.length; i++)
{
System.out.println(String.format("Movie %d rating is %d", i, result[i]));
}
}
PS: you are missing the validation around the String to int conversion and checks around the correctness of the user input
I currently have a text file in the format
matrix
row
a
b
c
row
d
e
f
row
g
h
i
row
j
k
l
matrix
row
m
n
o
p
q
row
r
s
t
u
v
I would like to convert this into two integer matrices (stored as 2 2D arrays), in the format
a b c
d e f
g h i
j k l
and
m n o p q
r s t u v
So far, I have created a Scanner object of the file and put each line in a text array:
Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // I added more than necessary for safety
while (sf.hasNext()){
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
This way, the text file is now contained in a string array, where each line is a new element of the array. Right now, I would like to partition the array into two arrays with each array being the matrices. How should I continue? (note: I am a total beginner and desire answers that are simple (no arraylist, hashmap, etc., and that's why this question is not a duplicate of How to read two matrices from a txt file in java because it uses BufferedReader, and there are other potential duplicate questions, so I would like to clear this up)
What I currently have after the top:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
if (counter = 0)
{
\\not yet written...
}
\\not yet written...
}
As #Rob said, it's really cumbersome to do this without dynamic data structures such as ArrayList's. But nevertheless, here's a code that does your job (considering you have only two matrices), without using any List's:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
int rowSize = 0, numberOfRows = 0;
counter = 2;
while (!text[counter].equals("row") && !text[counter].equals("matrix")) {
counter++;
rowSize++;
}
//now we have the row size
numberOfRows = 1;
while (!text[counter].equals("matrix")) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
//now we have the total number of rows
matrix1 = new int[numberOfRows][rowSize];
counter = 2; //to start from the first matrix
//now counter should point to the first row of the first matrix
while (!text[counter].equals("matrix")) {
jCounter = 0;
while (!text[counter].equals("row")
&& !text[counter].equals("matrix")) {
matrix1[iCounter][jCounter++] = Integer.parseInt(text[counter]);
//supposing your input is Integers, otherwise, you can change
//it to the corresponding type (i.e. Long, Double, etc)
counter++;
}
iCounter++;
if (!text[counter].equals("matrix"))
counter++;
}
//now we finished with the first matrix, and the counter points to
//the first "row" of the second matrix, so we do the same thing again
rowSize = 0;
numberOfRows = 0;
int startOfSecondMatrix = counter + 2; //save this for later
counter += 2; // so that counter points to the first number
while (counter < text.length && !text[counter].equals("row")) {
counter++;
rowSize++;
}
numberOfRows = 1;
while (counter < text.length) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
matrix2 = new int[numberOfRows][rowSize];
counter = startOfSecondMatrix;
iCounter = 0;
while (counter < text.length) {
jCounter = 0;
while (counter < text.length && !text[counter].equals("row")) {
matrix2[iCounter][jCounter++] = Integer.parseInt(text[counter]);
counter++;
}
iCounter++;
counter++;
}
For each matrix we perform the same operations:
-We first go through the matrix to count its size to be able to initialize it, after that, we go row by row, and parse each number.
You might as well put all the work for one matrix into a function (and take care of the bounds) and call it as long you still have more matrices.
This does what you want. Unfortunately doing this with 2D arrays is considerably harder since once you set the size of an array its difficult to manage changing it. Therefore using ArrayList is much easier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static final String MATRIX = "matrix";
public static final String ROW = "row";
public static void main(String[] args) throws FileNotFoundException {
// Use correct file name here
Scanner sf = new Scanner(new File("matrices.txt"));
// This is a List of 2D Lists
List<List<List<String>>> matrices = new ArrayList<>();
// easier to process lines as we're reading them in so we
// only iterate over the file once
while (sf.hasNext()) {
boolean hasBeenProcessed = false;
String inputValue = sf.nextLine();
switch (inputValue) {
case MATRIX:
ArrayList<List<String>> matrix = new ArrayList<>();
matrices.add(matrix);
hasBeenProcessed = true;
break;
case ROW:
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
currentMatrix.add(new ArrayList<String>());
hasBeenProcessed = true;
break;
}
if (!hasBeenProcessed) {
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
List<String> currentRow = getCurrentRow(currentMatrix);
currentRow.add(inputValue);
}
}
// Print out the results:
int i = 1;
for (List<List<String>> matrix : matrices) {
System.out.println("Matrix " + i);
for (List<String> row : matrix) {
for (String element : row) {
System.out.print(element + " "); // no newline until end of the row
}
System.out.println(); // new line
}
i++;
System.out.println(); // new line
}
}
private static List<String> getCurrentRow(List<List<String>> currentMatrix) {
int lastRow = currentMatrix.size() - 1;
return currentMatrix.get(lastRow);
}
private static List<List<String>> getMatrixBeingProcessed(List<List<List<String>>> matrices) {
int lastMatrix = matrices.size() - 1;
List<List<String>> currentMatrix = matrices.get(lastMatrix);
return currentMatrix;
}
}
Output:
Matrix 1
a b c
d e f
g h i
j k l
Matrix 2
m n o p q
r s t u v
Process finished with exit code 0
Since you don't want to use List and arrays can't be resized once initialized, this is not easy.
There are two ways: Read the file and initialize arrays knowing the size (as #Maaddy posted) or 'resizing' arrays. That's not possible but it is if you use Arrays.copyOf() so you can create a new array.
The idea is create a 'tridimensional' array where you can store: matrix, row and column; and then start to read the file.
Every time you find a word the entire array will be updated creating a new array with one length more.
If the word is 'matrix' the extra length will be added to the first position (the position who 'store' the matrix)
If the word is 'row' then the space will be added for the current matrix. So in this way, the current matrix will have one more array where store the column values.
If the word is other then is a value for the column. The column is resized and added to the correct position.
Note that if a word 'matrix' or 'row' is found, the new array is initialized with no length. This is because will be resized later, when is necessary.
The code is as follows:
//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File("path/matrices.txt"));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
String line = sf.nextLine();
if(line.equals("matrix")) {
//'Resize' array: Create new array with 1 more length and old data
arrays = Arrays.copyOf(arrays, arrays.length + 1);
//Start new matrix
arrays[++matrix] = new String[0][0];
row = -1;
column = -1;
}else if(line.equals("row")) {
//'Resize' matrix: Create a new array with 1 more length and old data
arrays[matrix] = Arrays.copyOf(arrays[matrix], arrays[matrix].length+1);
row++;
arrays[matrix][row] = new String[0];
column = -1;
}else{
//'Resize' matrix
column++;
arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row], arrays[matrix][row].length+1);
arrays[matrix][row][column] = line;
}
}
sf.close();
//Print result
for(int i = 0 ; i < arrays.length; i++) {
System.out.println("Matrix "+i);
for(int j = 0; j < arrays[i].length; j++ ) {
for(int k = 0; k < arrays[i][j].length; k++) {
System.out.print(arrays[i][j][k]+ " ");
}
System.out.println();
}
System.out.println();
}
And the result is:
Matrix 0
a b c
d e f
g h i
j k l
Matrix 1
m n o p q
r s t u v
I want to convert some integers into a * based on a rule. I can determine which places in the matrix it should convert, but cannot convert it.
I give the program the first matrix and it should return the second matrix:
5 4 5 5 8
5 4 6 4 1
3 4 5 4 6
7 8 4 3 6
5 4 5 5 *
5 4 * 4 1
3 4 5 4 6
7 * 4 3 6
my code is this:
for(int i=1; i<r-1; i++) {
for(int a=1; a<c-1; a++){
if(matrix[i-1][a] < matrix[r][a] && matrix[i+1][a] < matrix[r][a] && matrix[i][a-1] < matrix[r][a] &&
matrix[i][a+1] < matrix[r][a]) {
matrix[r][a] = *;
}
}
}
Edit:
The matrix is an int type. I can determine which locations in the matrix should be converted, however the convertion itself does not work.
I get this error: Error: Syntax error on token "*", invalid Expression
you can use matrix of type Integer instead of int and then mark a * cell with null
Then when printing or using matrix show null values with *
You could leave int[][] matrix, and e.g. mark a * cells with some illegal number (e.g. Integer.MAX_VALUE). And when you print or use this matrix, do like: System.out.print(matrix[i][k] != Integer.MAX_VALUE ? matrix[i][k] : '*')
public static void main(String... args) {
int[][] matrix = new int[5][5];
modifyMatrix(matrix);
print(matrix);
}
public static void modifyMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
if (isStar(row, col, matrix))
matrix[row][col] = Integer.MAX_VALUE;
}
private static boolean isStar(int row, int col, int[][] matrix) {
// TODO your condition to place a '*'
return false;
}
private static void print(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0, max = matrix[row].length; col < msx; col++) {
System.out.print(matrix[row][col] != Integer.MAX_VALUE ? matrix[row][col] : '*');
System.out.println(col != max - 1 ? ' ' : '\0');
}
System.out.println();
}
}
In an int matrix you can't put characters or symbols(like '*')
The easiest thing to do is to change the type of the matrix. You should use char instead of int.
char[][] matrix = new char[r][c];
If you want to use an element from the matrix for equations you can use the
Character.getNumericValue(matrix[i][j]);
With this code it will return the number and if it has not numeric value it will return -1
You can check this link for the getNumericValue
click here
you should create an new array of strings the size of your matrix.
then run trough your matrix and either add the number or change it into a string, like this:
public String[] convert(int[] matrix,int rule) {
String[][] arr = new String[matrix.length][matrix[0].length];
for(int i = 0;i<matrix.length;i++) {
for(int j = 0; j<matrix[i].length;j++) {
if(matrix[i][j] == rule)
arr[i][j] = "*";
else
arr[i][j] = String.valueOf(matrix[i][j]);
return arr;
So I am working on a assignment that deals with randomly generated arrays. Here is the assignment:
Write the following function that tests whether a two-dimensional list has four consecutive numbers of the same value, either horizontally, vertically, or diagonally. public static boolean isConsecutiveFour(int[][] values) Write a test program that prompts the user to enter the number of rows and columns of a two-dimensional list and then use a random number generator to fill the array and print it out. Display True if the list contains four consecutive numbers with the same value. Otherwise, display False.
I got everything else done, and it seems to work, but I am stuck on the randomly generating the array part. What is supposed to happen is the user is supposed to enter in the amount of rows and columns for an array, then it is generated. Then, the array is tested to find out whether or not four consecutive numbers exist. When I come to test the problem, it does not actually display the numbers. I am at a loss, and really confused ( Can anyone help me or give me a hint? It would be greatly appreciated. Thank You!
import java.util.Random;
import java.util.Scanner;
public class ConsecutiveFour {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter number of rows: ");
int rows = input.nextInt();
input.nextLine();
System.out.print("Enter number of columns: ");
int columns = input.nextInt();
input.nextLine();
int[][] matrix = new int[rows][columns];
// generate some random boolean values
boolean[] booleans = new boolean[10];
for (int i = 0; i < booleans.length; i++) {
booleans[i] = r.nextBoolean();
}
for (boolean b : booleans) {
System.out.print(b + ", ");
}
System.out.println("");
}
public static boolean isConsecutiveFour(int[][] values) {
boolean cons = false;
int
//tests horizontally
for (int r=0; r < rows; r++) {
for (int c=0; c < columns - 3; c++){
if (values[c][r] == values[c+1][r] &&
values[c][r] == values[c+2][r] &&
values[c][r] == values[c+3][r]) {
cons = true;
}
}
}
//tests vertically
for (int r=0; r < rows - 3; r++) {
for (int c=0; c < columns; c++){
if (values[c][r] == values[c][r+1] &&
values[c][r] == values[c][r+2] &&
values[c][r] == values[c][r+3]) {
cons = true;
}
}
}
//tests diagonally (going down and to the right)
for (int r=3; r < rows; r++) {
for (int c=0; c < columns - 3; c++) {
if (values[c][r] == values[c+1][r-1] &&
values[c][r] == values[c+2][r-2] &&
values[c][r] == values[c+3][r-3]) {
cons = true;
}
}
}
//tests diagonally (going down and to the left)
for (int r=0; r < rows - 3; r++) {
for (int c=0; c < columns - 3; c++) {
if (values[c][r] == values[c+1][r+1] &&
values[c][r] == values[c+2][r+2] &&
values[c][r] == values[c+3][r+3]) {
cons = true;
}
}
}
return cons;
}
}
To start both of the input.nextLine(); lines are unnecessary. Your input.nextInt(); will be enough to bring in the two values that you need.
It might be easier for you to generate the exact number of random numbers that you need. Seeing how this is an assignment i'll throw you some pseudo code to work through.
for (int i = 0; i < rows; i++) {
for (int k = 0; i < columns; k++) {
int ranNum // Generate random number
// Place random number in matrix[i][k]
}
}
// Send array through checks
Is this the problem you are having or am I misunderstanding your confusion?