trouble understanding passing 2d array to methods and displaying - java

With this program I am supposed to use methods to pass through to obtain user input to fill a 3x4 2d array. Then add the sum of the columns and display the results.
The int[][] grid = fillArray(); has an error that in[][] required. Why am I unable to call my method in the main? This is how the book says to do it along witih countless youtube videos.
public class SumOfColumns {
public static int sumColumn(int[][] m, int columnIndex) {
for (int column = 0; column < 4; column++) {
columnIndex = 0;
for (int row = 0; row < 3; row++) {
columnIndex += m[column][row];
}
}
return columnIndex;
}
public static void main(String[] args) {
***int[][] grid = fillArray();***
}
public static int[][] fillArray(int[][] userInput) {
Scanner input = new Scanner(System.in);
int[][] grid = new int[3][4];
System.out.println("Enter a 3x4 grid of numbers please: ");
for (int row = 0; row < grid.length; row++) {
for (int column = 0; column < grid[row].length; column++) {
grid[row][column] = input.nextInt();
}
}
return grid;
}
}

When you declare your fillArray function you gave it an input of int[][] userInput, but then when you call:
int[][] grid = fillArray();
you don't give fillArray and input of int[][]. If you remove the paramter from the fillArray function that should fix it. It would look like:
public static int[][] fillArray() {
// your code...
}

Related

Error when trying to print a transposed 2d array

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] ;
}
}

2D array not printing

I'm trying to make a 2D array that essentially acts as a room/grid - like a top-down view.
This code creates an array of dimensions row x col based on user input. I then have it initialize every cell with a "." to represent a space.
My question is, why, when I use the printRoom() method does it not print anything out at all? The double nested for-loops are running through the array, but nothing gets printed.
I know it has to do with the user input, because I tried just initializing with row = 5 and col = 5, and it printed just fine.
Thank you for your help.
Here is the Room Class:
public class Room
{
int row, col;
String[][] arr = new String[row][col];
//Room Constructor
public Room(int row, int col)
{
this.row = row;
this.col = col;
}
//Fills the Room with "."
public void fillRoom()
{
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = ".";
}
}
//Prints the entire room/grid
public void printRoom()
{
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j]);
System.out.println();
}
}
}
Here is my RoomTest class which contains main:
import java.util.*;
public class RoomTest
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int row, col;
System.out.println ("Enter room dimensions (row col)");
row = scan.nextInt();
col = scan.nextInt();
Room room1 = new Room(row,col);
room1.fillRoom();
room1.printRoom();
}
}
Here is the output when I run and enter user input:
Enter room dimensions (col row)
4 6
When you initialize your array, row and col are zero, so it is a 0x0 array.
As such, the guard condition in for (int i = 0; i < arr.length; i++) is immediately false, and so never executes.
You need to move the array initialization into the constructor:
arr = new String[row][col];
Try to add length of the 2D array here because before are initialized with zero:
int row= 4, col= 6;
String[][] arr = new String[row][col];
Or you can initialize it in Constructor like this:
String[][] arr;
//Room Constructor
public Room(int row, int col)
{
arr = new String[row][col];
this.row = row;
this.col = col;
}
And in your main method initialize the row and col :
int row= 4, col= 6;
To solve the problem create the array at the constructor of Room object:
int row, col;
String[][] arr = null
//Room Constructor
public Room(int row, int col)
{
this.row = row;
this.col = col;
arr = new String[row][col];
}

how to print an empty 2d array without getting a nullpointerexception

I am relatively new to Java and for a school project I need to print a 2D array. The base for this project is to print it with values null. But I can't put this into a for loop without getting a java.lang.NullPointerException. Can anybody help?
private int ROWS;
private int COLUMNS;
private int WIDTH;
private String[][] sheet;
private String[][] values;
private int precision;
public SpreadSheet(int rows, int cols, int width, int precision) {
this.ROWS = rows;
this.COLUMNS = cols;
/*this.WIDTH = width;
this.precision = precision;*/
}
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.println(sheet);
}
System.out.println("\n");
}
}
The main :
import java.util.Scanner;
public class DemoSpreadSheet {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
SpreadSheet sh = new SpreadSheet(4, 6, 15, 2);
sh.printSheet();
}
}
Make a small change to the SpreadSheet function:
public SpreadSheet(int rows;int cols;int width;int precision)
{
this.Sheet=new String[rows][cols];
/*creates an array with 4 rows and 6 columns..(assuming this is what you wanted to do)*/
}
There is also an error in your print sheet function:
System.out.println(Sheet); //illogical
/*sheet does not print the content of the array Sheet*/
Change this to:
System.out.println(Sheet[i][j]);
/*this will print null */
you need to initialisé your arrays.
sheet = new String[rows][cols]
This is an exemple you have other errors in you class.
This will do it (including better format):
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.print(sheet[i][j] + " ");
}
System.out.println();
}
}
However, you have not assigned a length to your sheet. That means, at some point (at the constructor most likely) you have to define:
sheet = new String[rows][cols];

Error in output on converting 2D String array to 1D String array

For a practice problem for my programming class we have:
"Define a method that returns the first row of a two-dimensional array of strings that has a string with the name “John”."
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
System.out.println(firstRow(b)); // line 8
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
After going through the debug process on Eclipse, my String array name is set to {"John", "Abby"}, however I am getting an ArrayIndexOutOfBoundsException error at lines 8 and 17 when attempting to run the program.
Confused on what to do to get this program to output the names "John" and "Abby."
Because of this line;
for (int row = 0; row < a.length; row++) {
The goal of firstRow(String[][] a) method is returning the first row of the array, thus, the line above should be as below;
for (int row = 0; row < 1; row++) {
Because that it traverse all of the elements of the array, it exceeds the size of the name array which has only a[0].length rooms, numerically, 2. ( String[] name = new String[a[0].length]; )
In order to make your code functional, there are two ways;
First Solution
Update the for loop conditional as written above, the test code is;
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
// for (int row = 0; row < a.length; row++) {
for (int row = 0; row < 1; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
The output is as below;
John Abby
You've noticed (you should), I've also updated the print line.
Second Solution
The second way to make your code functional is, returning only first row for a[][], which is actually is as easy as returning a[1]. The test code is;
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
return a[0];
}
And the output is;
John Abby
Hope that it helps.
I think you should switch the variables row and col in line 17.

How do I change a set array into a random sized array

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

Categories