How to change element in a matrix (2D array) using setter method? - java

I'm trying to make my personal sudoku generator in Java, but I have a problem with setter element method of the matrix.
Field Class:
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
//Change the element of the field
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}
Main:
// First Print
for (i = 0; i < field.getField().length; i++) {
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print(field.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i = input.nextInt();
System.out.println("Select Column");
j = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
field.setElement(i,j,n);
// Second Print
for (i = 0; i < field.getField().length; i++){
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print( field.getField()[i][j]);
}
I don't know why the second print is the same as the first one.

You are creating copies of the matrix in the setField and getField methods
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
Doing that in the method setElement you:
get a copy of the original matrix.
change an element of the copy
set a copy of the original matrix
Here your code with comments explaining each step:
public void setElement (int i, int j, int n) {
// 1 - Get a copy of the original matrix
getField()
// 2 - Change an element of the copy
[i][j] = n;
// 3.a - get a copy of the original matrix
// 3.b - Set the copy
setField(getField());
}
So the final effect doesn't change the original matrix.
You can have the desired result doing the following:
public void setField(int [][] field){
this.field = field;
}
public int[][] getField() {
return field;
}
//Change the element of the field
public void setElement (int i, int j, int n) {
field[i][j] = n;
}

// you do a copy of internal array
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
// and then chane element of this copy
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}

I ran your program. It is running ok. But, in the beginning, I was getting null pointer exception error. So, maybe you should consider changing following things:
Add private int[][] field = new int[3][3]; in MyBean class.
the main() method:
public static void main(String[] args) {
MyBean myBean = new MyBean();
myBean.setElement(0, 0, 113);
myBean.setElement(0, 1, 114);
myBean.setElement(0, 2, 115);
int i1,j1,n;
Scanner input = new Scanner(System.in);
//First Print
for (int i = 0; i < myBean.getField().length; i++) {
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print(myBean.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i1 = input.nextInt();
System.out.println("Select Column");
j1 = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
myBean.setElement(i1,j1,n);
//Second Print
for (int i = 0; i < myBean.getField().length; i++){
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print( myBean.getField()[i][j]);
}
input.close();
}

Related

Error: Variable declaration not allowed here

I get this error and I don't know what to do, please can some one tell me a good answer.
import java.util.*;
public class test{
public static int expand(int[] a,int n){
if (n==1)
return a;
if (n<=0)
return new int[0];
if(n<1)
int []c=new int[a.length*n];
for(int i=0;i<a.length;i++){
int num=a[i]/n;
for(int j=0;j<n;j++){
c[i*n+j]=num;
}
}
return c;
}
public static void main (String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("please enter the n number:");
int x=sc.nextInt();
System.out.println("please enter the size of array:");
int arr=sc.nextInt();
int []b=new int [arr];
for(int o=0;o<b.legnth;o++){
System.out.println("please enter the"+o+"number:");
b[o]=sc.nextInt();
}
System.out.println("Java tester"+b);
System.out.println("expanded form is"+expand(b,x));
}
}
I get this error:
variable declaration not allowed here
why though?
i dont think I can remove identifying it as an integer or else it wont work
The reason is that you are trying to declare an object in an if else scope but no are using curly braces { }
Change the code to:
if (n < 1) {
int[] c = new int[a.length * n];
}
Or declare int []c = new int [a.length] at the top of the function and assing without declaration
c = new int[a.length*n];
public static int[] expand(int[] a,int n){
int [] c = null;
if (n==1)
return a;
if (n<=0)
return new int[0];
if(n<1){
c = new int[a.length*n];
for(int i=0;i<a.length;i++){
int num=a[i]/n;
for(int j=0;j<n;j++){
c[i*n+j]=num;
}
}
}
return c;
}
I think what you wanted to achieve:
public static int[] expand(int[] a,int n) {
if (n==1)
return a;
if (n<=0)
return new int[0];
int []c =new int[0];
if(n<1) {
c = new int[a.length * n];
for (int i = 0; i < a.length; i++) {
int num = a[i] / n;
for (int j = 0; j < n; j++) {
c[i * n + j] = num;
}
}
}
return c;
}
errors in your code were related to incorrect return type(int instead of int[]), c out of scope in for-loop.

Tower of Hanoi using 2D arrays issue

I'm working on a Tower of Hanoi project for school which needs to ask the user how many disks there are and then it needs to create and then solve the tower with a visual included. How I decided to do it is by using 2D arrays and for the most part its working, my only problem is that I don't know how to move the disks while keeping it modular. Here is my code.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of disks");
int num = scan.nextInt();
int temp = num-(num-1);
int measure = num;
//initializing the towers
int[][] towers = new int[num][num];
for(int i = 0 ; i < num; i++)
{
for(int j=0; j <3; j++)
{
}
}
createRings(towers, num, temp);
moveDisk(towers,num);
}
// creating the rings
private static void createRings (int[][]towers, int num, int temp)
{
for(int i = 0; i<num; i++)
{
for(int j=0; j<3;j++)
{
towers[i][0] = temp;
}
temp = temp+1;
}
displayTower(towers, num);
}
// prints the array for display purposes
private static void displayTower (int[][] towers, int num)
{
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(towers[i][j]+"\t");
}
System.out.println();
}
}
//moves the numbers in the array that represents disks
private static void moveDisk(int[][]towers, int num)
{
System.out.println();
displayTower(towers, num);
}
Does anyone have any suggestions on what I could do?
I've changed your code a bit to make it more readable for me.
I changed the towers array. Now each tower is its own array inside the towers array (makes more sense IMHO).
Arrays in Java know their size. So you don't have to pass the length of the array as a parameter to every method.
I added a method getHighestIdx() which returns the index before the first 0 value in the array
I don't know, how the function moveDisk() was intended to work. I changed the declaration so that it makes sense to me. It now moves a disk from tower i to tower j
This should help you to implement the algorithm from the linked question.
Here is the changed code:
public static void main(String[] args) {
int numberOfRings = 6;
int[][] towers = new int[3][numberOfRings];
createRings(towers);
displayTowers(towers);
moveDisk(towers, 0, 2);
displayTowers(towers);
}
private static void createRings(int[][] towers) {
for (int j = 0; j < towers[0].length; j++) {
towers[0][j] = j + 1;
}
}
private static void displayTowers(int[][] towers) {
for (int i = 0; i < towers[0].length; i++) {
for (int j = 0; j < towers.length; j++) {
System.out.print(towers[j][i] + " ");
}
System.out.println("");
}
}
private static void moveDisk(int[][] towers, int fromIdx, int toIdx) {
int valToMove = towers[fromIdx][getHighestIdx(towers[fromIdx])];
towers[fromIdx][getHighestIdx(towers[fromIdx])] = 0;
towers[toIdx][getHighestIdx(towers[toIdx]) + 1] = valToMove;
}
private static int getHighestIdx(int[] tower) {
int i = 0;
while (i < tower.length && tower[i] != 0) {
i++;
}
return i - 1;
}

calculate the minimum value for each column in 2D array

I have a 2D array , iam trying to calculate the minimum value for each column and put the result in the result array.
the code bellow is calculating the minimum value for each row , how can i get the min value for each column.
import java.util.*;
class Test20 {
public static void main ( String [] args) {
int[][] array = {{6,3,9},
{0,8,2},
{3,7,5}};
Test20 test = new Test20();
System.out.print(Arrays.toString(test.mincol(array)));
}
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
}
Just change the loop the following way:
min = 0;
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[j][min]){
min=j;
}
result[i]=n[min][i];
}
Be aware that you instantiate your result array by the length of the first dimension in your array but later use the n[][] param for looping and access the length of the second dimension in your loop.
If your two dim array is for example 4x5, this will cause ArrayOutOfBoundsExceptions.
You only need to do the same thing but inverting the variables
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[min][j]){
min=i;
}
result[j]=n[min][j];
}
}
If your code is correct just change:
if(n[i][j]<n[i][min]){
min=j;
}
with
if(n[i][j]<n[result[i]][j]){
result[i]=i;
}
finally
for(int i=0;i<n.length;i++) result[i]=n[result[i][j];
you don't need min. But change
int [] result = new int[n.length];
to
int [] result = new int[n[0].length];
How about you transpose your two dimensional array like:
public static int[][] transpose (int[][] original) {
int[][] array = new int[original.length][];
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
array[i] = new int[original[i].length];
for (int j = 0; j < original.length; j++) {
array[i][j] = original[j][i];
}
}
}
return array;
}
and then call it as:
System.out.print(Arrays.toString(test.minrow(transpose(array))));
Or, if you want to go without transpose, this is how you can do:
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
Your for loop looks ok. Check the code below I fixed some minor issues.
Based on your code replace Class code with below:
public class Test {
public static void main(String[] args) {
int[][]array={{6,1,9}, {0,1,2}, {3,7,5}};
int[] test;
test = minrow(array);
for(int i=0; i<test.length; i++){
System.out.println(test[i]);
}
}
public static int[] minrow(int[][] n){
int [] result = new int[n.length];
int min;
for(int i=0;i<n.length;i++){
min=0;
for(int j=0;j<n[i].length;j++){
if(n[i][j]<n[i][min]){
min=j;
}
}
result[i]=n[i][min];
}
return result;
}
}

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.

Changing values in an array

Ok, so here are my codes (main method and method I'm trying to call)
I want my method "rotateRR" to basically take the value from board[0] and put it on [1] and keep doing that for that single row. For example:
old array -> [1][2][3][4][5] to become [5][1][2][3][4] <- what new array should look like.
but after I call my method, I put my regular input which should be "1 rr", but it returns the same array. I need to return the updated array from rotateRR method, but it doesn't let me add a return statement.
public class Numbrosia {
static int [][] board = new int[5][5];
public static void main(String [] args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();
}
}
Scanner input = new Scanner (System.in);
while (true){
showBoard();
System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();
if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}
}
}
public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");
}
}
//METHODS
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type
The main problem with the method is that it's not even doing what you described as the functionality:
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
Should be changed to:
public static void rotateRR (int [][] board){
// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];
// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}
// Set the first entry to temp
board[0] = temp;
}
So after that method your array you inserted as a parameter is changed the way you described above. Notice that you don't need a return type, since the change affects the original array (keyword call-by-reference).
You have made the function void therefore you cannot return anything from it. So what you need to do is change it from void to something like char * and then return the associated char * to solve your problem
Read this: http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html for any further doubts.
Change this:
public static void showBoard()
to this
public static return-type showBoard()

Categories