How come I'm getting a null pointer exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting a NullPointerException in the hanoi function when pushing the values from the input into the stack and I'm not sure why heres my code:
public class Hanoi {
public static Stack<Integer>[] towersOfHanoi = new Stack[4];
static int moves;
public static void hanoi(int n) {
for(int i = n; n > 0; i--) {
towersOfHanoi[1].push(i);
}
moveDisc(n, 1, 2, 3);
}
public static void moveDisc(int n, int j, int k, int l) {
moveDisc(n-1, j, k, l);
int i = towersOfHanoi[j].pop();
towersOfHanoi[k].push(i);
moves++;
moveDisc(n-1, l, j, k);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number of discs: ");
int n = in.nextInt();
in.close();
hanoi(n);
towersOfHanoi[1] = new Stack<Integer>();
towersOfHanoi[2] = new Stack<Integer>();
towersOfHanoi[3] = new Stack<Integer>();
System.out.println(moves);

You've initialized an array of Stacks, but you haven't actually allocated Stacks and put them in said Array. In your main() function, you should do something like:
for (int i = 0; i < 4; i++)
{
towersOfHanoi[i] = new Stack<Integer>();
}
Edit: Do this BEFORE you call hanoi(n). Otherwise, you're referencing objects before allocating them.

Related

Stack, Exception in thread "main" java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 11 months ago.
In the following java program, I am trying to implement a stack using array
class stack{
int size, top;
int arr[];
stack(int n){
size = n;
top = -1;
int arr[] = new int[size];
}
void push(int x){
++top;
if(top >= size){
System.out.println("Stack overflow");
top = size-1;
}
else{
System.out.println("Data pushed: "+x);
arr[top] = x;
}
return;
}
void pop(){
if(top < 0){
System.out.println("Stack Underflow");
}
else{
System.out.println("Data popped: "+arr[top]);
--top;
}
return;
}
}
public class test{
public static void main(String[] args){
stack S = new stack(3);
S.push(5);
S.push(6);
S.push(7);
S.push(8);
S.pop();
S.pop();
S.pop();
S.pop();
}
}
After the first "push" operation the program throws the error: Exception in thread "main" java.lang.NullPointerException .
I tried initializing the array out of the constructor and it solves the problem, so I wanted to know what is wrong with the approach given above?
class stack{
int size, top;
int arr[] = new int[100];
stack(int n){
size = n;
top = -1;
//int arr[] = new int[size];
}
int size, top;
int arr[];
stack(int n){
size = n;
top = -1;
int arr[] = new int[size]; // these creates a local variable arr
}
Your problem here is that you are not instantiating your instance member, but creating a second, local array.
int size, top;
int arr[];
stack(int n){
size = n;
top = -1;
arr = new int[size]; // Don't redeclare arr, but use the existing one
}
This should fix the issue.
stack(int n){
size = n;
top = -1;
int arr[] = new int[size];
}
In the constructor , you are creating a new local variable arr[].
The instance variable is still uninitialised.
And by default, the value given to it is null.
Hence when you are trying to call an action on it, it is throwing Null Pointer Exception
Try this:
stack(int n){
size = n;
top = -1;
arr[] = new int[size];
}
For better understanding of variable scoping refer to this :https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.3

i want to find the span of a array. Span is defined as difference of maximum value and minimum value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried by creating two functions for greatest and smallest values and then subtracting them .but the code doesn't seem to work
here's the code.See if u could help me out .im new to java and still learning.
import java.io.*;
import java.util.*;
public class Main{
public static void smler(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]<arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void grter(int arr[],int j){
for (int i=0;i<=j;j++){
if(arr[i]>arr[i+1]){
int temp =arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
grter(arr,n);
int y= arr[n];
smler(arr,n);
int z = arr[n];
System.out.println(y-z);
}
}
There are a lot of errors in your logic.
The for loop does not need to be <= it needs to be < otherwise you will get out of bounds exception.
The way you are calculating the min and max are wrong.
Here is an example for you to study that does what you are trying to accomplish:
import java.util.Scanner;
public class ArraySpan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter value:");
arr[i] = sc.nextInt();
}
int min = findMin(arr);
int max = findMax(arr);
System.out.println("The span of the array = " + (max - min));
sc.close();
}
static int findMax(int[] a) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
}
return max;
}
static int findMin(int[] a) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < min)
min = a[i];
}
return min;
}
}
and output:
Enter array size:
3
Enter value:
1
Enter value:
2
Enter value:
3
The span of the array = 2
It would better if you could look for complexity improvement.
Idea is to get the max and the min in best possible way and this can be achieved using any sorting techniques, let us assume your sort method runs in O(n log n) time, and then you just need to get the difference of 1st element(0 th index) and last element(n-1 th index).
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
// insert values into your array
if(arr.length >= 2){
sort(arr); // Implement your any sorting method
// Make sure that your arr has exactly n elements, ,
// Otherwise rest of the indices will all be zero(0)
System.out.println(arr[0]-arr[arr.length-1]); // last index is 'arr.length-1'
return; // Return from here
}
// arr has not sufficient elements to determine span
throw new UnsupportedOperationException("Invalid entry");
}
}
Index starts from 0 and it goes till n-1.
So, the condition in for-loop should be i<n instead of i<=n,for(int i=0;i<n;i++).
You have created 2 functions but it doesn't return any value nor changes anything. As you are passing the array by value, not by references.
You don't need the 2 functions, just one for finding max and min in linear, or sort the array in ascending order and array[0] will be the min and array[n-1] will be max.
There is an approach very similar to what you want to do.
import java.io.*;
import java.util.*;
public class Main{
public static int smler(int arr[],int N){
int smaller = arr[0];
for (int i=1;i<N;i++){
if(arr[i] < smaller){
smaller = arr[i];
}
}
return smaller;
}
public static int grter(int arr[],int N){
int greater = arr[0];
for (int i=0;i<N;i++){
if(arr[i] > greater){
greater = arr[i];
}
}
return greater;
}
public static void main(String[] args) throws Exception {
Scanner sc= new Scanner (System.in);
int n=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<=n;i++){
arr[i]=sc.nextInt();
}
System.out.println(grter(arr, n) - smler(arr, n));
}
}

Print all possible permutations of an array elements [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am working on a program,I have tried to find a way how to find all possible permutations of an array elements in Java, but it didn't work .
My code is:
public class Permutation {
public static void main(String[] args) {
int[] list = new int[3];
System.out.println("enter the elements of array");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
System.out.println(Arrays.toString(list));
int n = list.length;
permutation(list, n, 0);
}
public static void permutation(int[] list, int n, int l) {
if (l == n - 1) {
printArray(n, list);
return;
}
for (int i = 1; i < n; i++) {
swap(list, list[i], list[l]);
permutation(list, n, l + 1);
swap(list, list[i], list[l]);
}
}
public static void swap(int[] list, int x, int y) {
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
public static void printArray(int n, int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i]);
}
}
}
This code is continuously throws an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Permutation.swap(Permutation.java:34)
at Permutation.permutation(Permutation.java:27)
at Permutation.permutation(Permutation.java:28)
at Permutation.main(Permutation.java:15)
I'm not able to understand what to do in this program so that it'll produce desired output.
And what is the meaning of this error which is thrown by program??
you are getting this error because you are trying to access items, not in the array try changing
i = 0 in line 25

In place works for int[] but not for int in java [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
The value of int a remains same after calling function (testInPlaceInteger(a)) but for int[] arr changes after calling the function (squareArrayInPlace). Why is int a value not changing?
Following is my code:
public class Test {
public static void main(String[] args) {
int a = 5;
int[] arr = new int[] {3, 4};
Test test = new Test();
test.testInPlaceInteger(a);
test.squareArrayInPlace(arr);
System.out.println(a);
for (int i : arr) {
System.out.println(i);
}
}
public void testInPlaceInteger(int num) {
num *= num;
}
public void squareArrayInPlace(int[] intArray) {
for (int i = 0; i < intArray.length; i++) {
intArray[i] *= intArray[i];
}
}
}
Output:
5
9
16
Because int is a primitive type and is passed by value. However, intArray[i] is a memory location, so you can change the value within.

return values between 2 given integers (Specified in main) which can be divided by 3 in a function and return answer back to main method [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Q:
Obtain start and end integers in main method. Pass those two values into a separate function.Return all the numbers between those values (inclusive), which is divisible by 3 back to the main from the function.
I have done upto:
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
search(x,y);
}
public static void search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
System.out.println(arr[i]);
// count = count+1;
// return count;
}
}
}
}
Now my question is ..How can I return the array and print it in function and print it there??? this code works but in this, the values are getting printed in the function itself (but it should be printed in the main)...
Change it to
import java.util.*;
public class inbetween {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter range of values");
int x =in.nextInt();
int y =in.nextInt();
int[] result = search(x,y);
for (int i=0;i < result.length; i++)
System.out.println(result[i]);
}
public static int[] search(int a, int b) {
int length = (b-a)+1;
int [] arr = new int [length];
for(int i=0; i<length; i++)
{
a = a+1;
int c;
// int count=0;
c = a%3;
if (c==0) {
arr[i] = a;
}
}
return arr;
}
}
Create array in main
Pass reference to array to function to do work
Print array out in main
You need to return an array to main:
package com.stackoverflow.homework;
import java.util.Arrays;
import java.util.Scanner;
public class Homework {
public static void main(String[] args) {
int[] result;
Scanner in = new Scanner(System.in);
System.out.println("Enter range of values: ");
int x = in.nextInt();
int y = in.nextInt();
result = findNumbersBetween(x,y);
for(int i=0; i<result.length; i++) {
System.out.println(result[i]);
}
}
private static int[] findNumbersBetween(int a, int b) {
int[] temp = new int[(b-a)+1];
int x = a;
int i = 0;
while(x <= b) {
if(x % 3 == 0) {
temp[i] = x;
i++;
}
x++;
}
return Arrays.copyOfRange(temp, 0, i);
}
}
Also remember that first letter of class name should always be capitalized!

Categories

Resources