Null Pointer Exception - Printing 2d array - java

I'm having an issue with attempting to print a 2 dimensional array, I continually get a nullpointer exception at the first for loop in printArray(), and at printArray(). I do know what a nullpointerexception means, I'm just having a hard time understanding why I'm getting it. I've ran into this problem before while trying to print an array and it'd be great for me to finally figure this out.
import java.lang.*;
import java.util.*;
public class Board {
int N = 3;
static int [][] unittest;
//construct a board from an N-by-N array of blocks
//(where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randInt(0,9);
}
}
unittest = blocks.clone();
}
//generates random numbers in a range
private static int randInt( int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//board size N
public int size(){
return 0; //placeholder
}
//number of blocks out of place
public int hamming(){
return 0; //placeholder
}
//sum of manhattan distances between blocks and goal
public int manhattan(){
return 0;
}
//is this board the goal board?
public boolean isGoal(){
return true; //placeholder
}
//is the board solvable?
public boolean isSolvable(){
return true; //placeholder
}
//does this board equal y?
//Object because can only take objects
//does it use Comparable?
public boolean equals(Object y){
return true; //placeholder
}
//all neighboring boards
public Iterable<Board> neighbors(){
Stack<Board> placeholder = new Stack<Board>();
return placeholder;
}
//string representation of the board
public String toString(){
return "placeholder";
}
//unit test
private static void printArray(){
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
//prints out board
printArray(); //**NULL POINTER EXCEPTION
}
}

The problem lies in the test condition of printArray() function:
for (int i = 0; i < unittest.length; i++)
Here, unitest is a null object and when you try to apply length method on it, its throwing and exception.
Basically, you are not initializing the unittest object (2D array in your case). You can do something like this to avoid the exception:
private static void printArray(){
if(unittest == null)
System.out.println("its NULL");
else{
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
}
Hope it helps :)

static int [][] unittest;
is null when you call it
you have never initialized the array, nor put anything into it

Beyond initializing the array you have an off by one error
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){ <----------------- blocks length should be blocks.length-1
for (int j = 0; j < blocks[i].length; j++){ <---------------------also blocks [i].length - 1
blocks[i][j] = randInt(0,9);
}

Related

Matrix diagonal

I would like to let you know that I'm new to this platform, I'm trying to solve this question, could anyone help me?
statement
The user must be prompted for the size of the matrix to be created. After user input, a square matrix is ​​created with the information obtained.
Example: The user entered the value 3 so we will have it.
[][][]
[][][]
[][][]
However, when printing the matrix on the screen, the diagonal must be filled with the values ​​1 and the value 0 for the other positions, but the diagonal must start on the right side. Example of the expected solution:
[0][0][1]
[0][1][0]
[1][0][0]
I think this question I would start by figuring out how to create the matrix with input, then I would probably keep some type of pointer that starts at the end of the first row as it is being built then I would decrement the pointer after each row till I am at index 0 of the last row with the pointer value in this case an integer.
I will code it below:
import java.util.*;
public class QuestionOne {
public static int[][] createMatrix(Integer n) {
int pointer = n - 1;
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer == j) {
matrix[i][j] = 1;
pointer--;
continue;
}
matrix[i][j] = 0;
}
}
return matrix;
}
public static void printMatrix(int[][] matrix, int n) {
for(int i = 0; i < n; i++) {
for(int k = 0; k< n-1; k++) {
System.out.print(matrix[i][k] + ",");
}
System.out.print(matrix[i][n-1]);
System.out.println("");
}
}
public static void main(String[] args) {
System.out.print("Enter a number for declaring size:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] mat = createMatrix(n);
printMatrix(mat, n);
}
}

Java set/setElementAt not setting the right value

I need to find all the permutations for a given n(user input) without backtracking.
What i tried is:
import java.util.Scanner;
import java.util.Vector;
class Main {
private static int n;
private static Vector<Vector<Integer>> permutations = new Vector<>();
private static void get_n() {
Scanner user = new Scanner(System.in);
System.out.print("n = ");
n = user.nextInt();
}
private static void display(Vector<Vector<Integer>> permutations) {
for (int i = 0; i < factorial(n) - 1; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
}
System.out.println();
}
}
private static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
private static int max(Vector<Integer> permutation) {
int max = permutation.elementAt(0);
for (int i = 1; i < permutation.size(); ++i)
if (permutation.elementAt(i) > max)
max = permutation.elementAt(i);
return max;
}
// CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION
public static int validate_permutation(Vector<Integer> permutation) {
// GOOD NUMBER OF ELEMENTS
if (max(permutation) != permutation.size() - 1)
return 0;
// PROPER ELEMENTS APPEAR
for (int i = 0; i < permutation.size(); ++i)
if (!permutation.contains(i))
return 0;
return 1;
}
private static Vector<Integer> next_permutation(Vector<Integer> permutation) {
int i;
do {
i = 1;
// INCREMENT LAST ELEMENT
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
// IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW"
while (permutation.elementAt(permutation.size() - i) == permutation.size()) {
// RESET CURRENT POSITION
permutation.set(permutation.size() - i, 0);
// INCREMENT THE NEXT ONE
++i;
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
}
} while (validate_permutation(permutation) == 0);
// OUTPUT
System.out.print("output of next_permutation:\t\t");
for (int j = 0; j < permutation.size(); ++j)
System.out.print(permutation.elementAt(j) + " ");
System.out.println();
return permutation;
}
private static Vector<Vector<Integer>> permutations_of(int n) {
Vector<Vector<Integer>> permutations = new Vector<>();
// INITIALIZE PERMUTATION SET WITH 0
for (int i = 0; i < factorial(n); ++i) {
permutations.addElement(new Vector<>());
for(int j = 0; j < n; ++j)
permutations.elementAt(i).addElement(0);
}
for (int i = 0; i < n; ++i)
permutations.elementAt(0).set(i, i);
for (int i = 1; i < factorial(n); ++i) {
// ADD THE NEXT PERMUTATION TO THE SET
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
System.out.print("values set by permutations_of:\t");
for (int j = 0; j < permutations.elementAt(i).size(); ++j)
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
System.out.println("\n");
}
System.out.print("\nFinal output of permutations_of:\n\n");
display(permutations);
return permutations;
}
public static void main(String[] args) {
get_n();
permutations.addAll(permutations_of(n));
}
}
Now, the problem is obvious when running the code. next_permutation outputs the correct permutations when called, the values are set correctly to the corresponding the vector of permutations, but the end result is a mass copy of the last permutation, which leads me to believe that every time a new permutation is outputted by next_permutation and set into the permutations vector, somehow that permutation is also copied over all of the other permutations. And I can't figure out why for the life of me.
I tried both set, setElementAt, and an implementation where I don't initialize the permutations vector fist, but add the permutations as they are outputted by next_permutation with add() and I hit the exact same problem. Is there some weird way in which Java handles memory? Or what would be the cause of this?
Thank you in advance!
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
This is literally setting the vector at permutations(i) to be the same object as permutations[i-1]. Not the same value - the exact same object. I think this the source of your problems. You instead need to copy the values in the vector.

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

why wont main recieve my returned int value java

so when I go to compile this Eclipse says, that the numbers for Insertionct and Shakerct are 0 and prints out a tie. I know for a fact that both methods are sorting correctly, but for some reason it doesn't return the amount of comparisons that they are making to main in order to decide which one sorted the array faster. Thanks for any help in advance.
import java.io.*;
import java.util.*;
public class Sorts {
private static Scanner in;
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
System.out.print("How many strings will you be entering? ");
int sz = Integer.parseInt (in.nextLine());
String[] A = new String[sz];
String[] B = new String[sz];
for (int i = 0; i < sz; i++){
System.out.print ("Enter String #"+(i+1)+": ");
A[i] = in.nextLine();// sets the array at i equal to a string
B[i] = A[i]; // sets array B to the same as array A so I can use it in the shaker sort method
}
int Insertionct = 0;
int Shakerct = 0;
System.out.println(Insertionct);
System.out.println(Shakerct);
if (Shakerct > Insertionct) {
System.out.println("Insertion Sort was faster!");
} else if (Shakerct < Insertionct) {
System.out.println("Shaker Sort was faster!");
} else {
System.out.println("It was a tie");
}
}
public static int InsertionSort (int Insertionct, String[] A) throws Exception { //sorts the array of strings with the insertion sort.
// initializes the count variable
int sz = A.length; // sets size equal toe array A
for (int i = 0; i < sz-1; i++)
for (int j = i; j >= 0 && A[j].compareTo (A[j+1]) > 0; j--) {
Insertionct++;
String t = A[j]; //switch A[j], A[j+1]
A[j] = A[j+1];
A[j+1] = t;
}
return Insertionct;
}
public static int ShakerSort (int Shakerct, String[] B) throws Exception {//Uses the ShakerSort in order to order the array.
int sz = B.length;
for (int i = 0; i < sz; i++){
int nsct = 0;
for(int j = nsct+sz-1; j > i; j--){//runs through the array backwards and then swaps if it needs to
Shakerct++;
if (B[j].compareTo(B[j-1]) < 0) {
nsct = 0;
String t = B[j];
B[j] = B[j-1];
B[j-1] = t;
} else {
nsct++; // if no swap happens it increases no swap to increment the starting points.
}
}
for (int j = nsct; j > sz-i-1; j++){
if (B[j].compareTo(B[j+1]) > 0){//runs through the array going forward swaps if needed
Shakerct++;
nsct = 0;
String t = B[j];
B[j] = B[j+1];
B[j+1] = t;
} else {
nsct++;// increases no-swap count if no swap happens and changes the starting point.
}
}
}
return Shakerct;
}
}
You don't call InsertionSort and ShakerSort in main.

two quick fix issues - Merge Sort

I have created my version of the merge sort algorithm in java code. My issues are these: when I run the code as is, I get a NullPointerExecpetion in the main on line 27 (see commented line). And I know there is way to make the method calls and instantiate newArray without them being static but Im not quite sure how.. can someone help fix these? I am still relatively new to java so be nice :)
Main:
import java.util.Random;
public class MergeSort_main
{
public static void main(String[] args)
{
int[] originalArray = new int[1000];
Random rand = new Random();
for (int i = 0; i < originalArray.length; i++)
{
int randNum = rand.nextInt(1000)+1;
originalArray[i] = randNum;
}
for(int i = 0; i < originalArray.length; i++)
{
System.out.println(i+"." + originalArray[i]);
}
System.out.println("---------------------End Random Array-------\n");
MergeSortAlgorithm.mergeSortAlg(originalArray);
int[] sortedArray = MergeSortAlgorithm.getSortedArray();
for(int i = 0; i < sortedArray.length; i++) //NULL POINTER EXCEPTION HERE
{
System.out.println(i+ "." + sortedArray[i]);
}
}
}
Algorithm Class:
public class MergeSortAlgorithm
{
private static int[] newArray;
public static void mergeSortAlg(int[] randomNums)
{
int size = randomNums.length;
if (size < 2)
{
return; //if the array can not be split up further, stop attempting to split.
}
int half = size / 2;
int firstHalfNums = half;
int secondHalfNums = size - half;
int[] firstArray = new int[firstHalfNums];
int[] secondArray = new int[secondHalfNums];
for (int i = 0; i < half; i++)
{
firstArray[i] = randomNums[i];
}
for (int i = half; i < size; i++)
{
secondArray[i - half] = randomNums[i];
}
mergeSortAlg(firstArray);
mergeSortAlg(secondArray);
merge(firstArray, secondArray, randomNums);
}
public static void merge(int[] firstArray, int[] secondArray, int[] newArray)
{
int firstHalfNums = firstArray.length;
int secondHalfNums = secondArray.length;
int i = 0; //iterator for firstArray
int j = 0; //iterator for second array
int k = 0; //interator for randomNums array
while (i < firstHalfNums && j < secondHalfNums)
{
if (firstArray[i] <= secondArray[j])
{
newArray[k] = firstArray[i];
i++;
k++;
}
else
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
while (i < firstHalfNums)
{
newArray[k] = firstArray[i];
k++;
i++;
}
while (j < firstHalfNums)
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
public static int[] getSortedArray()
{
return newArray;
}
}
Basically, the only problem with your code is that you don't initialize newArray with any values, resulting in a null.
You are also redefining newArray at the top of your merge function .
The problem is that newArray[] is never instantiated i.e. newArray reference is pointing to null. And, no change is made in the newArray so value or reference returned to main is null. And, then you are performing sortedArray.length where sorted array having a null value.
You have to make newArray[] point to randomNums[].

Categories