Java 2D array with user input - java

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

Related

How to display anything into an array that changes based on user input?

Basically I have to make a random word search generator for my class, and I can get user input to create how many rows and how many columns the word search will have, and I can make my program ask the user to input x amount of words to find (based on rows) and the length of the words(based on columns) however for the life of me I can not find out how to print anything inside of this mysterious grid I have made. I just need to find out how to add random letters inside of the array/grid/board. Thanks.
import java.util.*;
public class Assignment2 {
Scanner keyboard = new Scanner(System.in);
private int[][] wordBoard;
private char[][] gameBoard;
private String[] wordList;
private static int row;
private static int col;
Random rnd = new Random();
public void playWordSearch() {
wordBoard = numRowCol();
wordStorage(wordBoard);
}
/**
* This method asks the user to input an integer for Rows/Columns
* And gracefully handles invalid input :)
*
* #return
*/
public int[][] numRowCol() {
int array[] = new int[100];
boolean again = true;
while (again) {
for (int i = 0; i <= 1; i++) {
try {
if (i == 0) {
System.out.printf("Enter a number of rows (2-15): %n");
array[i] = keyboard.nextInt();
if (array[i] > 15 || array[i] < 2) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
}
}
} catch (InputMismatchException e) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
keyboard.next();
e.printStackTrace();
}
try {
if (i == 1) {
System.out.printf("Enter a number of columns (2-15): %n");
array[i] = keyboard.nextInt();
if (array[i] > 15 || array[i] < 2) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
}
}
} catch (InputMismatchException e) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
keyboard.next();
e.printStackTrace();
}
}
again = false;
}
System.out.printf("The amount of rows you have entered: %d%nAnd the amount of columns: %d%n", array[0], array[1]);
int[][] arrayArray = new int[array[0]][array[1]];
return arrayArray;
}
public int wordStorage(int[][] arrayArray) {
int size;
String word[] = new String[arrayArray.length];
int sizeRow = arrayArray.length;
int sizeCol = arrayArray[1].length;
System.out.printf("rows: %d%n", sizeRow);
System.out.printf("cols: %d%n", sizeCol);
for (int i = 0; i < arrayArray.length; i++) {
System.out.printf("Enter a word with less than %d characters: %n", sizeCol);
word[i] = keyboard.next();
}
keyboard.close();
System.out.println(Arrays.deepToString(arrayArray).replace("], ",
"]\n").replace("[[", "[").replace("]]", "]"));
return 100;
}
}
import java.util.*;
public class Assignment2 {
Scanner keyboard = new Scanner(System.in);
private char[][] wordBoard;
private char[][] gameBoard;
private String[] wordList;
private static int row;
private static int col;
Random rnd = new Random();
public void playWordSearch() {
wordBoard = numRowCol();
wordStorage(wordBoard);
}
public static void main(String[] args) {
Grid grid = new Grid();
grid.playWordSearch();
}
/**
* This method asks the user to input an integer for Rows/Columns
* And gracefully handles invalid input :)
*
* #return
*/
public char[][] numRowCol() {
int array[] = new int[100];
boolean again = true;
while (again) {
for (int i = 0; i <= 1; i++) {
try {
if (i == 0) {
System.out.printf("Enter a number of rows (2-15): %n");
array[i] = keyboard.nextInt();
if (array[i] > 15 || array[i] < 2) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
}
}
} catch (InputMismatchException e) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
keyboard.next();
e.printStackTrace();
}
try {
if (i == 1) {
System.out.printf("Enter a number of columns (2-15): %n");
array[i] = keyboard.nextInt();
if (array[i] > 15 || array[i] < 2) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
}
}
} catch (InputMismatchException e) {
System.out.printf("Requirements: int between [2-15] %n");
i -= 1;
keyboard.next();
e.printStackTrace();
}
}
again = false;
}
System.out.printf("The amount of rows you have entered: %d%nAnd the amount of columns: %d%n", array[0], array[1]);
char[][] arrayArray = new char[array[0]][array[1]];
return arrayArray;
}
public int wordStorage(char[][] arrayArray) {
int size;
String word[] = new String[arrayArray.length];
int sizeRow = arrayArray.length;
int sizeCol = arrayArray[1].length;
System.out.printf("rows: %d%n", sizeRow);
System.out.printf("cols: %d%n", sizeCol);
for (int i = 0; i < arrayArray.length; i++) {
System.out.printf("Enter a word with less than %d characters: %n", sizeCol);
word[i] = keyboard.next();
}
keyboard.close();
for (int i = 0; i < word.length; ++i) {
arrayArray[i] = word[i].toCharArray();
}
System.out.println(Arrays.deepToString(arrayArray).replace("], ",
"]\n").replace("[[", "[").replace("]]", "]"));
return 100;
}
}
First, your grid was a 2d int array not a 2d char array for your words (your functions also returned a 2d int array instead of a 2d char array). Second, I just added a simple for loop to assign user input of words into the array.
If you need to fill the empty spaces from the columns, simply generate random char values, fill the char arrays to meet the size values, then assign them into the array like I did above.

Java Program to Determine if there are any Duplicate Rows in the Matrix of a 2-Dimensional Array?

So, as the title says, I'm trying to put together a program that will compare the rows of a 2-dimensional array and determine if any rows are identical.
This has to be accomplished in two parts; determining whether any rows are identical and determining how many rows are identical. I'm trying to use a Boolean method to determine whether there are any identical rows and a separate method to determine how many rows are identical if the Boolean method returns true.
For example, if the array were:
1 2 3
2 3 1
1 2 3
Then the Boolean method would return true and the output would be:
The matrix has 2 identical rows.
The issue is that I don't know how I should set up the Boolean method; if I could figure that much out, the rest of the program would be simple to figure out.
How can I set up the Boolean method for this?
Here's the code I've come up with so far if anyone needs it:
public class IdenticalRows {
public static void main(String[] args) {
Scanner KBin = new Scanner(System.in);
char run;
int ROW, COL;
System.out.println("Would you like to begin? (Y/N)");
run = KBin.next().charAt(0);
do {
if(run!='y' && run!='Y' && run!='n' && run!='N') {
System.out.println("Please only type 'y' or 'Y' to begin or type 'n' or 'N' to close the program.");
System.out.println("Would you like to begin? (Y/N)");
run = KBin.next().charAt(0);
}
}while(run!='y' && run!='Y' && run!='n' && run!='N');
do {
System.out.println("Please enter the number of rows:");
ROW = KBin.nextInt();
do {
if (ROW<=0) {
System.out.println("Entry invalid; must be a positive integer greater than 0.");
System.out.println("Please enter the number of rows:");
ROW = KBin.nextInt();
}
}while(ROW<=0);
System.out.println("Please enter the number of columns:");
COL = KBin.nextInt();
do {
if (COL<=0) {
System.out.println("Entry invalid; must be a positive integer greater than 0.");
System.out.println("Please enter the number of columns:");
COL = KBin.nextInt();
}
}while(COL<=0);
int[][] testDuplicates = new int[ROW][COL];
randArray (testDuplicates, MIN, MAX);
System.out.println("Thematrix is:");
printArray(testDuplicates);
System.out.println(" ");
boolean presence = duplicates(testDuplicates);
if (presence=true) {
countDuplicates(testDuplicates);
}
else if (presence=false) {
System.out.println("There are no identical rows in this matrix.");
}
System.out.println("Would you like to run the program again? (Y/N)");
run = KBin.next().charAt(0);
}while(run=='y' || run=='Y');
}
public static void randArray(int[][] matrix, int low, int up) {//Establishes the values of the elements of the array
Random rand = new Random();
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] = rand.nextInt(up-low+1)+low;
}
}
}
public static void printArray(int[][] matrix) {//Prints the elements of the array in a square matrix
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.printf("%5d",matrix[r][c]);
}
System.out.println(" ");
}
}
public static boolean duplicates(int[][] list) {//Determines if any row(s) of elements ever repeat
for (int r=0; r<list.length; r++) {
for (int c=0; c<list[r].length; c++) {
}
}
return false;
}
public static void countDuplicates(int[][] matrix) {
for (int r=0; r<matrix.length; r++) {
for (int c=0; c<matrix[r].length; c++) {
}
}
}
public static final int MAX=3;
public static final int MIN=1;
}
Thank you in advance to anyone who can help!
First of all write the method that compares two rows:
private static boolean areIdentical(int[] a1, int[] a2) {
if(a1.length != a2.length) return false;
for(int i = 0; i < a1.length; i++) {
if(a1[i] != a2[i]) return false;
}
return true;
}
Now you can use this method to compare the rows. Just take every row from the array and compare it with every row below. Something like the next:
public static boolean duplicates(int[][] list) {
for (int j = 0; j < list.length; j++) {
if(j == list.length-1) return false; //don't need to compare last row
for (int i = j + 1; i < list.length; i++) {
if(areIdentical(list[j], list[i])) return true;
}
}
return false;
}
You can easily modify this code to count duplicates.

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 Methods & Demo

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 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