Program Compiles, but array out of bounds when ran? - java

My code compiles fine, but when I run it I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Sudoku.(Sudoku.java:20) at Test.main(Test.java:7)
The code is as follows:
Main Test class:
public class Test {
public static void main(String[] args) {
Sudoku puzzle;
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
boolean somethingChanged=true;
while(somethingChanged) {
somethingChanged=false;
System.out.println(puzzle);
for (int i=0; i<puzzle.size; i++)
for(int j=0; j<puzzle.size; j++)
if(puzzle.oneOption(i, j)!=puzzle.EMPTY) {
// exactly one value can be filled in at location i,j
// do this now, and record that something has changed
// compared to the previous iteration of the while loop
puzzle.setValue(i,j,puzzle.oneOption(i,j));
somethingChanged=true;
}
}
// if oneOption is implemented correctly, the puzzle is now solved!
System.out.println(puzzle);
}
}
and my uncommented Sudoku Class:
class Sudoku {
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
int [][] cellGrid = new int [cellHeight][cellWidth];
public Sudoku(int a, int b){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
}
public Sudoku(int a, int b, int array[][]){
cellHeight = a;
cellWidth = b;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}
public Sudoku(){
cellHeight = 3;
cellWidth = 3;
size = cellHeight*cellWidth;
for(int i = 0; i<size; i++)
for(int j = 0; j<size; j++)
sudGrid[i][j] = 0;
}
public void setValue(int r,int c, int v){
sudGrid[r][c] = v;
}
public int getValue(int r, int c){
return sudGrid[r][c];
}
public void clear(int r, int c){
sudGrid[r][c] = EMPTY;
}
public String toString(){
String message = "";
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
message = message + sudGrid[i][j];
if (j == cellWidth){
message = message + " ";
}
}
message = message + "\n";
}
return message;
}
public int oneOption(int r, int c){
return 1;
}
}
Sorry, I know this is a lot of code to splat on the screen, but I haven't done a lot on arrays, let alone two dimensional. I know my oneOption() method at the moment does nothing, I just needed it to compile, but where the errors are, is
int temp = array[i][j];
sudGrid[i][j] = temp;
and
int[][] entries = {{1,0,0,0},{0,0,0,3},{0,0,4,0},{0,4,0,0}};
puzzle = new Sudoku(2,2,entries);
Now I assumed where the entries array is declared is correct as this is code that my lecturer has set up for us, and we are only designing the Sudoku class. and I was trying to make the values of the entries array, go into the sudGrid array, I assumed I did it correctly, but im getting the exception error,
any ideas?

Your subgrid is defined as a zero length two dimensional array, so you can't fit anything in there.
See here:
int cellHeight, cellWidth, size,EMPTY = 0;
int [][] sudGrid = new int[cellHeight * cellWidth][cellHeight * cellWidth];
cellHeight and cellWidth are initialized to zero by default, then you create a new int[0*0][0*0] array.
Change your constructor to the following:
public Sudoku(int a, int b, int array[][]){
cellHeight = a; // Changing these two instance variables will *NOT*
cellWidth = b; // retrofit your subGrid to a new size.
size = cellHeight*cellWidth;
subGrid = new int[size][size];
for(int i = 0; i<size; i++){
for(int j = 0; j<size; j++){
int temp = array[i][j];
sudGrid[i][j] = temp;
}
}
}

You're setting your Sudoku.size to be the entire number of cells in the puzzle, and then trying to read that many rows and columns. You need to iterate just to the number of columns and rows.

Related

How to move LinkedList element values into arrays and putting array elements into a linkedlist

i have a project that uses linkedlists and arrays to create matrices and vectors that are commonly seen in mathematics. I was wondering how you could take the values of linkedlist nodes and store them in an array. The project asks to move elements from a linkedlist Matrix(SparseMatixLinkedList), as the matrix is formed through the construct of an array, and move its values into an array to make it a Matrix through the construct of an array (DenseMatrix).
Would anybody know how to do this, and vice-versa if i wanted to move the elements in the array matrix back into the linkedlist matrix? (The SparseMatrix and DenseMatrix methods are below the commented phrase 'for app 5').
import java.util.*;
interface Matrix
{
Vector VecArray[][] = new Vector[]{
// Assign the value x to element i,j
public void set(int i,int j, double x){
for(int i =0; i < data.length; i++){
data[i] = x;
}
}
// i = data [i][i];
// get the value of the element i,j
double get(int i, int j);
// Extract the diagonal of the matrix
double[] getDiagonal();
// get the size of the matrix-- number of rows
public int getSize(){
this.size = size;
return size;
}
int count = 0;
// for (RowNode r = head; r != null; r = r.next){
// count++;
// }
return count;
}
// get the number of non-zero elements
int getNnz(){
int i;
int j;
int [][] aElements = new int [i][j];
for (int k = 0 ; k < aElements.length; k++){
int x = aElements.length;
int y = aElements[0].length;
int result = x * y;
return result;
}
}
// Multiply a matrix by a vector
Vector multiply(Vector B);
public static int[][] multMatrix(int a[][], Vector B){//a[m][n], b[n][p]
if(a.length == 0) return new int[0][0];
if(a[0].length != B.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = B.getSize();
// int ans[][] = new int[m][p];
double[] newV = new double [B.getSize()];
int value;
for(int i = 0; i < n; i++){
value = 0;
for(int j = 0; j < m; j++){
value += a[i][j] * B.get(i);
}
newV[i] = value;
}
// for(int i = 0;i < m;i++){
// for(int j = 0;j < p;j++){
// for(int k = 0;k < n;k++){
// ans[i][j] += a[i][k] * B[k][j];
// }
// }
// }
// return ans;
// }
// }
// Vector A;
// Vector B;
// for(int i = 0; i < VecArray.length; i++){
// for(int j = 0; j < VecArray.length; j++){
//
// Vector k = A * B;
// }
// }
// Print matrix using a specific format
public void display();
for (int row = 0; row < x.length; row++) {
for (int column = 0; column < x[row].length; column++) {
System.out.print(x[row][column] + "\t");
}
System.out.println();
System.out.println("This is the first array");
display(firstarray);
System.out.println("This is the second array");
display(secondarray);
// return info about the matrix
void info();
//List<Double> SparseMatrixLinkedList = new LinkedList<Double>(Arrays.asList(1.0, 2.0));
}
//////////////////////////////////// ARRAY DENSE MATRIX IMPLEMENTATION
class DenseMatrix implements Matrix
{
//////// TO COMPLETE--you can uncomment the instructions below
private int size=0; // size of the matrix- number of rows/columns
private int nnz=0; // number of non-zero elements
private double[][] data;
public DenseMatrix(int n) {
// TODO Auto-generated constructor stub
}
/////// return info about the matrix
public void info(){
System.out.println("Dense Matrix n="+size+", nnz="+nnz+", Storage="+(8*size*size)+"b or "+(8*size*size)/(1024*1024)+"Mb");
}
}
//////////////////////////////////// Linked-List SPARSE MATRIX IMPLEMENTATION
//public RowNode rArray[] = new RowNode (100){
//
//public ColNode cArray[] = new ColNode (100){
//
//}
data[][] = new Object [RowNode] [ColNode];
class RowNode{
public int rowindex;
public ColNode col;
public RowNode next;
RowNode(int i){rowindex=i; col=null; next=null;}
}
class ColNode{
public double entry;
public int colindex;;
public ColNode next;
ColNode(int j,double x){
colindex=j;
entry=x;
next=null;}
}
class SparseMatrixLinkedList implements Matrix
{
List<RowNode> r1 = new LinkedList<RowNode>();
Node c1 = new LinkedList <ColNode>();
// int l;
// if(Link l : r1){
// l = new LinkedList<ColNode>(1,2);
// }
private RowNode top;
private int size=0;
private int nnz=0;
// constructors
// Basic constructor- no element in the list yet
SparseMatrixLinkedList(DenseMatrix, size, nnz){
top=null;
first = newLink;
}
}
//for App 5:
SparseMatrixLinkedList(DenseMatrix, size, nnz){
LinkedList<SparseMatrixLinkedList> mlinkedlist = new LinkedList<SparseMatrixLinkedList>();
// (DenseMatrix, size, nnz){
// top=null;
// first = newLink;
for(int i = 0; i < size; i++){
mlinkedlist.add(data[i]);
}
DenseMatrix(SparseMatrixLinkedList){
mArray[] = new DenseMatrix [size];
for(int i = 0; i < size; i++){
mArray[i] = new link;
}
}
Linkedlist S&EMatrix = new LinkedList <Matrix>(nnz, size){
}
// methods
public void vectorArray(){
}
public void display(){
RowNode current = top; //start probe at the beginning
System.out.println("i");
while (current!=null) { // until the end of the list
System.out.print(current.rowindex+" ");
ColNode jcurrent = current.col;
while (jcurrent!=null) { // until the end of the list
System.out.format("==> (j=%d, a=%.4f)",jcurrent.colindex,jcurrent.entry);
jcurrent = jcurrent.next;
}
System.out.println();
current = current.next; // move to next Link
}
System.out.println();
}
// return info about the matrix
public void info(){
System.out.println("Sparse Matrix n="+size+", nnz="+nnz+", Storage="+(8*nnz)+"b or "+(8*nnz)/(1024*1024)+"Mb");
}
}

return new int[]{randomHeight, randomWidth};

I want to code some basic stuff for a little minesweeper-game, that we do in university. Now I have the problem that my code .
public class Minesweeper1 {
public static int[][] makeRandomBoard(int s, int z, int n){
//creating the field and fill with 0
int feld[][] = new int [s][z];
for(int i = 0; i < s; i++){
for(int j = 0; j < z; j++){
feld[i][j] = 0;
}
}
//n-times to fill the field
for( int i = 0; i < n; i++){
selectRandomPosition(s, z);
//want to get them from selectRandomPosition
feld[randomHeight][randomWidth] = 1;
}
}
}
So it starts the selectRandomPosition code:
public static int[] selectRandomPosition(int maxWidth, int maxHeight) {
int randomHeight = StdRandom.uniform(0, maxHeight);
int randomWidth = StdRandom.uniform(0, maxWidth);
return new int[]{randomHeight, randomWidth};
}
Here I'm not allowed to change anything, but it returns a new array. Now is my question how can I use the new array in my makeRandomBoard method, since I do not know any name of the array. When I use feld[randomHeight][randomWidth] = 1;, it says that it doesn't know these variables.
how I can use the new array in my makeRandomBoard method, since I do not know any name of the array?
Call the method, and assign its return value to a variable. Now you have a name for the array:
// Make a call
int[] randomArray = selectRandomPosition(maxW, maxH);
// Access the width
int randomW = randomArray[0];
// Access the height
int randomH = randomArray[1];

Null Pointer Exception Error in a DoubleMatrix class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm having trouble with a java problem. I get this error:
Exception in thread "main" java.lang.NullPointerException
at DoubleMatrix.getDim1Size(DoubleMatrix.java:28)
at Program3.main(Program3.java:16)
I don't understand where it is null
public class DoubleMatrix
{
private double[][] doubMatrix;
public DoubleMatrix(int firstDim, int secondDim, double upperLimit)
{
if(firstDim > 0 && secondDim > 0 && upperLimit > 0){
firstDim = 1;
secondDim = 1;
upperLimit = 1;
}
}
public DoubleMatrix(double[][] tempArray)
{
if(tempArray != null && tempArray.length != 0){
for(int i =0; i < tempArray.length; i++) {
doubMatrix = tempArray;
}
}
else{
tempArray = new double[1][1];
}
}
public int getDim1Size(){
int firstDim1 = doubMatrix.length;
return firstDim1;
}
public int getDim2Size(){
int secondDim1 = doubMatrix[0].length;
return secondDim1;
}
private void makeDoubMatrix(int firstDim, int secondDim, double upperLimit){
double[][] randomMatrix = new double[firstDim][secondDim];
for(int row = 0; row < doubMatrix.length; row++) {
for(int column = 0; column < doubMatrix[row].length; column++){
doubMatrix[row][column] = (double)(Math.random() * 100);
}
}
}
public DoubleMatrix addMatrix(DoubleMatrix arrayObj)
{
if(doubMatrix.length == arrayObj.doubMatrix.length && doubMatrix[0].length == arrayObj.doubMatrix[0].length){
double[][] TotalTwoDimArray = new double[doubMatrix.length][doubMatrix[0].length];
for(int row = 0; row < TotalTwoDimArray.length; row++){
for(int column = 0; column < TotalTwoDimArray[row].length; column++){
TotalTwoDimArray[row][column] = doubMatrix[row][column] + arrayObj.doubMatrix[row][column];
}
}
return new DoubleMatrix(TotalTwoDimArray);
}
return new DoubleMatrix(1, 1, 1);
}
public DoubleMatrix getTransposedMatrix(){
double[][] TransMatrix = new double[doubMatrix[0].length][doubMatrix.length];
for(int row = 0; row < doubMatrix.length; row++){
for(int column = 0; column < doubMatrix[row].length; column++){
TransMatrix[row][column] = doubMatrix[column][row];
}
}
return new DoubleMatrix(TransMatrix);
}
public DoubleMatrix multiplyMatrix(DoubleMatrix obj1)
{
if(doubMatrix[0].length == obj1.doubMatrix.length){
double[][] multipliedMatrix = new double[doubMatrix.length][obj1.doubMatrix[0].length];
for(int i = 0; i < multipliedMatrix.length; i++){
for(int j = 0; j < multipliedMatrix[i].length; j++){
for(int k = 0; k < doubMatrix[0].length; k++){
multipliedMatrix[i][j] = doubMatrix[i][k] * obj1.doubMatrix[k][j] + multipliedMatrix[i][j];
}
}
}
return new DoubleMatrix(multipliedMatrix);
}
return new DoubleMatrix(1, 1, 1);
}
public void printMatrix(String titles){
System.out.println(titles);
for(int row = 0; row < doubMatrix.length; row++){
for(int column = 0; column < doubMatrix[row].length; column++){
System.out.printf("%9.1f", doubMatrix[row][column]);
}
System.out.println();
}
}
}
// main in different class
public class Program3
{
public static void main(String[] args)
{
DoubleMatrix doubMatObj1;
DoubleMatrix doubMatObj2;
DoubleMatrix doubMatObj3;
int max = 10;
int min = 3;
int firstDim = (int)(Math.random() * (max - min + 1) + min);
int secondDim = (int)(Math.random() * (max - min + 1) + min);
doubMatObj1 = new DoubleMatrix(firstDim, secondDim, 100.);
doubMatObj2 = new DoubleMatrix(doubMatObj1.getDim1Size(), doubMatObj1.getDim2Size(), 100.);
doubMatObj3 = doubMatObj1.addMatrix(doubMatObj2);
doubMatObj1.printMatrix("First Matrix Object");
doubMatObj2.printMatrix("Second Matrix Object");
doubMatObj3.printMatrix("Result of Adding Matrix Objects");
doubMatObj2.printMatrix("Result of Transposing Matrix Object");
doubMatObj1.multiplyMatrix(doubMatObj2);
doubMatObj3.printMatrix("Result of Multiplying Matrix Objects");
}
}
In java, non primitives don't get initialized by just declaring them. So if you get a NullPointerException in a line like foo.bar(), you know that foo had to be null. In your case you have doubMatrix.length, which indicates that doubMatrix has never been initialized. Looking at your code, only the second constructor ever initializes that variable, so calling the first constructor will leave doubMatrix==null to always be true.
I hope that is enough info to help you fix your problem yourself (and similar problems in the future), but I am not going to post a working code example, since fixing your code yourself will be a good exercise!
On a sidenote, in your second constructor you have:
for(int i =0; i < tempArray.length; i++) {
doubMatrix = tempArray;
}
If tempArray.length is for example 5, you would assign the same value 5 times to the same variable. I don't know what you are trying to do there, but it is certainly not what you had in mind.

A method that calls an array and returns a different array is giving a can't resolve B to a variable error

I am calling one array and returning another array that is sorted based on the other array.
I think my method is proper but when I try to print out from the new array in the main method i'm getting an error that reads,
"Cannot resolve B to a variable."
B is the name of the new array that my method should return.
Thanks in advance.
package sort;
public class SortByFinal {
public static int [][] sortByFinal(int n, int [][] A)
{
int [][]B = new int [n][3];
int max = 0;
for(int i =0; i<n; i++)
{
for(int j = i; j<n; j++)
{
max = Math.max(A[i][1], max);
}
for(int k = i; k<n; k++)
{
if(A[k][1] == max)
{
B[k][0] = A[k][0];
B[k][1] = A[k][1];
B[k][2] = A[k][2];
}
}
}
return B;
}
public static void main(String []args)
{
int num = 5;
int[][] now = new int [num][3];
now[0][0] = 2342;
now[0][1] = 88;
now[0][2] = 98;
now[1][0] = 3901;
now[1][1] = 75;
now[1][2] = 71;
now[2][0] = 1444;
now[2][1] = 60;
now[2][2] = 85;
now[3][0] = 5327;
now[3][1] = 95;
now[3][2] = 80;
now[4][0] = 4888;
now[4][1] = 83;
now[4][2] = 100;
//int [][] B = new int[num][3];
sortByFinal(num, now);
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(B[i][j]);//this gives me the "B cannot be resolved to a variable."
System.out.print(" ");
}
System.out.println();
}
}
}
B is defined in sortByFinal(), but not in main(). To fix this, you could change your main to the follow:
int[][] B = sortByFinal(num, now);
Since sortByFinal(num, now) returns a int[][], this will work.
In your code, you're calling the function, but not doing anything with the return value, and you do not have access to the local variables of other methods; hence, the message.

non static variable called from static content, java

I know this question was answered before, but I cant still handle it with my code.
Please can someone pointing out how can I fix it on this particular code. Id like to call trace(); but dont know where to call new trace. I tried different stuff from here but it does not work for me. Thank you!
package matr;
import java.util.Scanner;
final public class Matrix {
private final int M;
private final int N;
private double[][] data;
public Matrix(int M, int N) {
this.M = M;
this.N = N;
data = new double[M][N];
}
public Matrix(double[][] data) {
M = data.length;
N = data[0].length;
this.data = new double[M][N];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.data[i][j] = data[i][j];
}
private Matrix(Matrix A) {
this(A.data);
}
public static Matrix random(int M, int N, int r) {
Matrix A = new Matrix(M, N);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A.data[i][j] = (Math.random() * r);
}
}
return A;
}
public double trace() {
// trace a = new trace();
double t = 0;
for (int i = 0; i < Math.min(M, N); i++) {
t += data[i][i];
}
return t;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("rows: ");
try {
int x = Math.abs(scan.nextInt());
System.out.println("columns: ");
int y = Math.abs(scan.nextInt());
System.out
.println("generate: ");
int r = scan.nextInt();
Matrix A = Matrix.random(x, y, r);
System.out.println("random A");
trace();
} catch (java.util.InputMismatchException e) {
System.out.println("Please enter a valid int");
}
}
}
call A.trace()
use lower-case names for variables and fields
your main method is static. and your trace() method is a non-static method of the Matrix class. That means you have to call trace() on an instance of Matrix.
You are trying to call a non-static method trace() from a static method main(). Since 'main' is static it can only refer to static variables and static methods within the class. You will need to use an instance of Matrix to call trace. for example:
Matrix A = Matrix.random(x,y,r);
A.trace();
You need to call the trace() method on an instance of the type Matrix.
You could do this simply by:
A.trace();

Categories

Resources