While writing my code I'm getting stuck on I'm trying to return the new transposed array and actually transposing the array itself. I get the error cannot convert int to int[][]. i thought trans would be an array var. the problem code is at the way bottom. any help is greatly appreciated.
package workfiles;
import java.util.*;
import java.util.Scanner;
public class hw2 {
// Do not modify this method
public static void main(String[] args) {
try
{
int [][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);
int [][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
}
catch (InputMismatchException exception)
{
System.out.println("The array entry failed. The program will now halt.");
}
}
// A function that prints a 2D integer array to standard output
// It prints each row on one line with newlines between rows
public static void print2DIArray(int[][] output) {
for (int row = 0; row < output.length; row++) {
for (int column = 0; column < output[row].length; column++) {
System.out.print(output[row][column] + " ");
}
System.out.println();
}
}
// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException {
int row=0;
int col=0;
int arow=0;
int acol=0;
int holder;
Scanner numScan = new Scanner(System.in);
while (row<=0){
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}
while (col<=0){
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}
int[][] iArray = new int[row][col];
while (arow < row) {
while (acol < col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
iArray[arow][acol] = holder;
acol++;
}
if (acol >= col) {
acol = 0;
arow ++;
}
}
//arrayName[i][j]
numScan.close();
return iArray;
}
//!!! problem code here!!!
public static int[][] transposition(int [][] iArray) {
int m = iArray.length;
int n = iArray[0].length;
int trans[][];
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans = iArray[y][x] ;
}
}
return trans;
}
}
You missed two things
1.) initialization of trans
int trans[][]= new int [n][m];
2.) trans is a 2D array
trans[y][x] = iArray[y][x] ;
//trans = iArray[y][x] ; error
Update : To form this logic , we need index mapping like this
// trans iArray
// assign values column-wise row-wise
// trans[0][0] <= iArray[0][0]
// trans[1][0] <= iArray[0][1]
// trans[2][0] <= iArray[0][2]
mean traverse the iArrays row-wise and assign values to trans array columns-wise
int m = iArray.length;
int n = iArray[0].length;
// iArray[2][3]
int trans[][] = new int[n][m];
// 3 2
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans[x][y] = iArray[y][x] ;
}
}
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);
}
}
}
}
im stuck on a problem with my java program in when I input numbers it will return index out of bounds error. the line is 66 wheres its getting caught up on.
arrayName[row][col] = holder;
any help in figuring out the problem would be most helpful. full program below
package workfiles;
import java.util.*;
import java.util.Scanner;
public class prob2 {
// Do not modify this method
public static void main(String[] args) {
try
{
int [][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);
int [][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
}
catch (InputMismatchException exception)
{
System.out.println("The array entry failed. The program will now halt.");
}
}
// A function that prints a 2D integer array to standard output
// It prints each row on one line with newlines between rows
public static void print2DIArray(int[][] output) {
}
// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException {
int row=0;
int col=0;
int arow=0;
int acol=0;
int holder=0;
Scanner numScan = new Scanner(System.in);
while (row<=0){
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}
while (col<=0){
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}
int[][] arrayName = new int[row+1][col+1];
while (arow < row) {
if (acol<=col)
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
// !!!line 66 begins right here!!!
arrayName[arow][acol] = holder;
acol ++;
if (acol>col)
acol=0;
arow ++;
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
arrayName[arow][acol] = holder;
acol ++;
}
//arrayName[i][j]
numScan.close();
return arrayName;
}
public static int[][] transposition(int [][] arrayName) {
int r=0, c=0;
int[][] transpose = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
transpose[i][j] = arrayName[j][i];
}
}
return transpose;
}
}
I reinstalled eclipse to my computer and removed one while loop, which kept setting values to zero, and changed it to an if statment so it only happend once, I can't explain how or why that was running a out of bounds error, but the program works correctly now.
package workfiles;
import java.util.*;
import java.util.Scanner;
public class hw2 {
// Do not modify this method
public static void main(String[] args) {
try
{
int [][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);
int [][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
}
catch (InputMismatchException exception)
{
System.out.println("The array entry failed. The program will now halt.");
}
}
// A function that prints a 2D integer array to standard output
// It prints each row on one line with newlines between rows
public static void print2DIArray(int[][] output) {
int iArray[][];
for (int row = 0; row < iArray.length; row++) {
for (int column = 0; column < iArray[row].length; column++) {
System.out.print(iArray[row][column] + " ");
}
System.out.println();
}
}
// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException {
int row=0;
int col=0;
int arow=0;
int acol=0;
int holder;
Scanner numScan = new Scanner(System.in);
while (row<=0){
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}
while (col<=0){
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}
int[][] iArray = new int[row][col];
while (arow < row) {
while (acol < col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
iArray[arow][acol] = holder;
acol++;
}
//this is where i replaced the while loop for the if statment, in the while loop it kept on resetting the acol value. there was no need to loop that part of the program.
if (acol >= col) {
acol = 0;
arow ++;
}
}
//arrayName[i][j]
numScan.close();
return iArray;
}
public static int[][] transposition(int [][] iArray) {
int r=0, c=0;
int[][] transpose = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
transpose[i][j] = iArray[j][i];
}
}
return transpose;
}
}
Give this a try:
if (acol <= col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
arrayName[arow][acol] = holder;
acol++;
}
if (acol > col) {
acol=0;
arow ++;
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
arrayName[arow][acol] = holder;
acol++;
}
The output of this program works fine. But there's one thing I've not been able to implement. In some cases, I don't have a row or column with the highest number of 1s. Sometimes I have 2 or more rows/columns which have the same "HIGHEST" number of ones. But my program only returns 1 row/column.
I want a case whereby If i have more than 2 rows/columns with the same highest number of 1s. Both rows will be displayed. e.g. "Row(s) with the most 1's: 1,2" or if it's a column it can say "Row(s) with the most 1's: 1,2".
Please I need help with this. I'm stuck.
import java.util.Random;
import java.util.Scanner;
public class LargestRowColumn
{
// declare a 2 dimensional array or an array of arrays
private static int[][] randArray;
public static void main(String[] args)
{
do
{
// Create a scanner to get Input from user.
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter the array size n:");
int rows = scanner.nextInt();
int cols = rows;
randArray = new int[rows][cols];
// loop through the number of rows in thw array
for (int i = 0; i < randArray.length; i++)
{
// loop through the elements of the first array in the array
for (int j = 0; j < randArray[0].length; j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
}
// make a linebreak each row.
System.out.println();
}
System.out.print("Row(s) with the most 1's: " + scanRow(randArray) + "\n");
System.out.print("Columns(s) with the most 1's: " + scanColumn(randArray) + "\n");
}
while(true);
}
// quick method I made to get a random int with a min and max
public static int getRandomInt(int min, int max)
{
Random rand = new Random();
return rand.nextInt(max-min+1)+min;
}
public static int scanRow(int[][] array)
{
int result = -1;
int highest = -1;
for (int row = 0; row < array.length; row++)// Here we are about start looping through the matrix values
{
int temp = 0; // Setting the first index to 0.
for (int col = 0; col < array[row].length; col++)//
{
//Assign current location to temporary variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = row + 1;
}
}
return result;
} // end of row method
private static int scanColumn(int[][] array)
{
int result = -1;
int highest = -1;
// declare and initialize the variable(here you've 'created' it, to then call it on if statement)
int col = 0;
for (int row = 0; row < array.length; row++)
{
int temp = 0;
//declare the variable in the for loop
for (col = 0; col < array[row].length; col++)
{
//Assign current location to temp variable
temp = temp + array[row][col];
}
if (temp > highest)
{
highest = temp;
result = col;
}
}
return result;
}
}
I would suggest a different approach, first thing why do you need to loop all over the 2D array again , u can figure out the highest 1's in rows and columns while inserting them and insert them in an array ( array of rows and array for columns) the carry will be of custom type which is a class with two parameters , score(which is number of 1's) and index( which is the number of the row or column), then sort the arrays and print the indexes related to top scores.
if you are expecting to receive the array with the inputs you can do the same but with new loop.
so your insert loop will be like this
List<Wrapper> rowsList = new ArrayList<Wrapper>(rows);
List<Wrapper> colsList = new ArrayList<Wrapper>(cols);
for(int i=0;i<cols;i++) {
colsList.add(new Wrapper(i,0));
}
// loop through the number of rows in thw array
for (int i = 0; i < rows; i++)
{
int sum =0;
// loop through the elements of the first array in the array
for (int j = 0; j < cols j++)
{
// set a random int 0-1 to the array
randArray[i][j] = getRandomInt(0, 1);
// print the number just assigned
System.out.print(randArray[i][j]);
sum+=randArray[i][j];//add for row
colsList.get(j).setScore(colsList(j).getScore() +randArray[i][j]);//add for column
}
rowsList.add(new Wrapper(i,sum));
// make a linebreak each row.
}
Collections.sort(rowsList,new Comparator<Wrapper>() {
#Override
public int compare(Wrapper obj1,Wrapper obj2) {
if(obj1.getScore() > obj2.getScore())
return -1;
if(obj1.getScore() < obj2.getScore())
return 1;
return 0;
}
});
if(rowsList.isEmpty())
return -1;
int max = rowsList.get(0).getScore();
for(Wrapper obj:rowsList) {
if(obj.getScore()< max)
break;
System.out.println(obj.getIndex);
}
//DO THE SAME FOR COLUMNS
your wrapper class will be
public class Wrapper {
private int index;
private int score;
public Wrapper(int index,int score) {
this.index = index;
this.score = score;
}
public int getIndex() {
return this.index;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score
}
}
This is in keeping with the OP use of arrays.
Instead of returning an int, which would be one row, you can return int[].
Personally, I would init the int[] to the number of rows in the array, because what if every row has the same number of 1's?
int[] results = new int[array[0].length];
Then, instead of adding in the rows, I would have a variable used to designate which spot to add the row to, i.e., results[0] etc.
int index = 0;
Then, all it takes is a small adjustment to how you add your results to the array.
public static int[] scanRow(int[][] array)
{
int highest = -1;
int index = 0; //ADD HERE
int[] results = new int[array[0].length]; //ADD HERE
... //Your code here
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
for(int x = 0; x < results.length; x++){
results[x] = -1;
}
index = 0; //RESET THE INDEX
results[index] = row + 1;
index ++;
} else if (temp == highest{
highest = temp;
results[index] = row + 1;
index ++;
}
}
return results;
} // end of row method
Personally, I would use an ArrayList for these types of things, so heres how I would do it using it.
I would make the return type of the method an ArrayList<int>.
public static ArrayList<int> scanRow(int[][] array)
Then declare my ArrayList<int>
ArrayList<int> results = new ArrayList<>();
and the if statements are a little easier to handle, since ArrayList as a clear() and add() method.
if (temp > highest)
{
highest = temp;
//CLEAR THE RESULT LIST
results.clear();
results.add(row+1);
} else if (temp == highest{
highest = temp;
results.add(row + 1);
}
EDIT
Don't forget to edit your print statements accordingly.
I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.
How do I change a set array sized into a random sized array chosen by the user.
Here is how I have it setup for set a sized array. I just do not know how to convert over to a random sized....
import java.util.Scanner;
public class Project1a {
public static void scanInfo()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
int rows = input.nextInt();
System.out.println("Enter number of columns: ");
int columns = input.nextInt();
int[][] nums = new int[rows][columns];
static int[][] sample = nums;
}
static int[][] results = new int[4][5];
static int goodData = 1;
public static void main(String[] args) {
analyzeTable();
printTable(results);
}
static void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
static void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount; // instead of print
xCol++;
}
}
static int analyzeCell(int row, int col) {
int xCol = col; // varies in the loop
int runCount = 0; // initialize counter
int rowLen = sample[row].length; // shorthand
int hereData = sample[row][xCol]; // shorthand
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
/* Start Print Stuff */
public static void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public static void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}
/* End Print Stuff */
I am now only getting one error at line 18: illegal start of expression. I do not think I have the variables defined correctly.
You could re-write your code in order to use ArrayList's:
import java.util.ArrayList;
//Here you create an 'array' that will contain 'arrays' of int values
ArrayList<ArrayList<Integer>> sample = new ArrayList<ArrayList<Integer>>();
then add each row:
sample.add(new ArrayList<Integer>());
and add an element to a row:
sample.get(0).add(5); // get(0) because is the first row, and 5 is int
Of course you will have to modify your code to use this kind of array.
You can't change array sizes in Java, although it gets complicated when working with multi-dimensional arrays. I would recommend familiarizing yourself with the Java Array docs.
What you can do is create a new array of the desired size and then copying data from the old array into the new one.
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: "); // get number of rows
int rows = input.nextInt();
System.out.println("Enter number of columns: "); // get number of columns
int columns = input.nextInt();;
int[][] nums = new int[rows][columns]; // new 2D array, randomly
// sized by user input
Is this all you're looking for? Based off your question, that's what it seems like
If you want a method populate it with random 1's and 0's, Just do this
static void populate(int[][] nums) {
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < column.length; i++) {
nums[row][column] = (int)(Math.random() + 1);
}
}
}
Now num is a 2D matrix with random 1's and 0's