I am trying to do a push and pop operation on stack and trying to pop minimum element from stack. It is showing null pointer exception. I tried debugging it. But still it is throwing null point exception.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Stacks {
static void Stack_Push(Stack<Integer> SP, int a)
{
SP.push(new Integer(a));
System.out.println("stack: " + SP);
}
static void stack_pop(Stack<Integer> SP) {
System.out.print("Popping Minimum Element ");
int n = 0, k = 0;
final int [] pop_array = null;
while (!SP.empty()){
int pop_elem = SP.pop();
pop_array[k++] = pop_elem;
}
for (int i = 1; i < n; i++) {
int j = i;
int B = pop_array[i];
while ((j > 0) && (pop_array[j-1] > B)) {
pop_array[j] = pop_array[j-1];
j--;
}
pop_array[j] = B;
}
System.out.println("stack: " + pop_array[0]);
}
public static void main(String args[]) throws IOException {
Stack<Integer> st = new Stack<Integer>();
int num, n;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(ir);
System.out.print("Enter number of elements : ");
String str = bf.readLine();
num = Integer.parseInt(str);
for(int i = 0; i < num; i++){
System.out.print("Enter elements : ");
str = bf.readLine();
n = Integer.parseInt(str);
Stack_Push(st, n);
}
stack_pop(st);
try {
stack_pop(st);
}
catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
In the stack_pop method, you're trying to affect value to a null array:
final int [] pop_array = null;
...
pop_array[k++] = pop_elem;
You should initialize it with the number of elements contained in your Stack.
There are other problems in this method too, like:
for (int i = 1; i < n; i++)
where n is defined to 0 at the beginning and never changed.
And why are you calling two times stack_pop(st)? The second call will always be made with an empty stack. If it was to test if the exception is caught, the line
System.out.println("stack: " + pop_array[0]);
makes your program crash as your trying to access pop_array[0] whereas you initialized your array with the size of the stack, which was 0.
In the code below, you are setting pop_array to null and then trying to work with it. This is your problem.
final int [] pop_array = null;
while (!SP.empty()){
int pop_elem = SP.pop();
pop_array[k++] = pop_elem;
}
You did not initialize your pop_array:
final int [] pop_array = null;
Try this:
final int [] pop_array = new int[SP.size()];
Also you might need a guard around your sysout:
if (pop_array.length > 0) {
System.out.println("stack: " + pop_array[0]);
}
pop_array is not initialized at,
final int [] pop_array = null;
change it into,
final int [] pop_array = new int [SP.size()];
Related
I am doing this for a Codeforces question. The entry I am testing is as follows:
5 2 (new line)
1 3 1 4 2
The question for those curious is https://codeforces.com/problemset/problem/450/A
Anyways, I am currently trying to manipulate a hashmap and rearrange entries but I am getting a null pointer for the line (indicate below): int num = fullInfo.get(i)[0];
I don't quite understand why because I have tested the statement and the hashmap does contain the appropriate array and the array is not empty either, so there should be no reason I am getting a null pointer.
Note: I apologize, I have an extra hashmap there labelled as info but I am not using it for anything so please pay no heed to that.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[]line = br.readLine().split(" ");
int a = Integer.parseInt(line[0]);
String [] secondLine = br.readLine().split(" ");
HashMap<Integer,Integer> info = new HashMap<>();
HashMap<Integer, Integer[]> fullInfo = new HashMap <>();
for(int i = 0; i < a; i++){
info.put(i, Integer.parseInt(secondLine[i]));
Integer [] array = {Integer.parseInt(secondLine[i]), i};
fullInfo.put(i, array);
}
int i = 0;
int amt = Integer.parseInt(line[1]);
while(fullInfo.size() > 1){
int num = fullInfo.get(i)[0]; //null pointer here
if(num <= amt){
fullInfo.remove(i);
}
else {
int lastKey = fullInfo.size()-1;
int currentVal = fullInfo.get(i)[0]-amt;
int ogIndex = fullInfo.get(i)[1];
Integer [] curr = {currentVal, ogIndex};
int lastVal = fullInfo.get(lastKey)[0];
int lastIndexOG = fullInfo.get(lastKey)[1];
Integer [] last = {lastVal, lastIndexOG};
fullInfo.put(i, last);
fullInfo.put(lastKey, curr);
}
}
System.out.println(fullInfo);
}
}
Even though I have parsed it to an integer value I'm still getting an error. I need to get the integer value from a String input where I remove the comma and space, and store it in an array, then I convert that array to an integer array
import java.util.ArrayList;
import java.util.Scanner;
public class SeriesSolution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
ArrayList<Integer> modes = new ArrayList<>();
for (int x = 0; x < count; x++) {
String lines = sc.nextLine();
String[] strs = lines.split(", ");
int[] array = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
if (Integer.parseInt(strs[i]) > 0 && Integer.parseInt(strs[i]) < 100) {
array[i] = Integer.parseInt(strs[i]);
}
}
modes.add(mode(array));
}
for (int y:modes){
System.out.println(y);
}
}
private static int mode(int a[]) {
int maxValue=0, maxCount=0;
for (int anA : a) {
int count = 0;
for (int anA1 : a) {
if (anA1 == anA) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = anA;
}
}
return maxValue;
}
}
The issue is mainly because Scanner accepts Enter keystroke as input. And because of which
String lines = sc.nextLine();
this peice of code stores an empty string into lines variable. This empty string throws NumberFormatException when passed to parseInt()
I would recommend you to use BufferedReader with InputStreamReader
BufferedReader br = new BuffereedReader(new InputStreamReader(System.in));
This is good for larger inputs and is error free. Though empty checks are must as prevention is better.
If you want to use Scanner, I would recommend you to update the code and use the below snippet of code.
String lines = "";
while (lines.equals("")) {
lines = sc.nextLine();
}
Do a check before the parseInt
if (strs[i] != null && !"".equals(strs[i]) && Integer.parseInt(strs[i]) ...
Or surround it with a try catch to catch the NumberformatException that will happen if a string is inserted instead of a number
import java.io.*;
import java.util.*;
public class chopMiddle {
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
}
}
I try to break the string into tokens and uses Integer.parseInt method to convert the tokens into int value.
I want to return an array of size 3 which contains the int values of the 2nd to the 4th integers from the string to the caller. Am i doing something wrong, because it shows below message when i compiled
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at chopMiddle.main(chopMiddle.java:18)
The problem will be when it gets to the 5th token, it will read it, then create a new array and try to read 3 more.
After you have read the 2nd, 3rd and 4th, you should break both loops.
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) //check hasMoreTokens
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
you need to check every time when you call: tokenizer.nextToken()
If you check if tokenizer has more elements in the for loop itself then you won't require while loop at all.
try below example :
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
int[] array = new int[3];
for (int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
During the method call compute(ee, temp1, s1, k) from method smaller() the argument value which am passing is not same as the one which am receiving, can someone help me with this issue?
*This is my problem statement-Get the least number after deleting k digits from the input number. For example, if the input number is 24635,the least number is 23 after deleting 3 digits.
I am expecting the final output to be 23 but getting infinite loop.
public class Delete3 {
public static void main(String[] args) {
int k = 3;
int num = 24635;
StringBuffer num1 =new StringBuffer(Integer.toString(num));
int temp = 0;
StringBuffer s = new StringBuffer(num1);
temp = Integer.parseInt(s.deleteCharAt(0).toString());
temp = compute(num1, temp, s, k);
System.out.println(temp);
}
static int compute(StringBuffer num2, int temp, StringBuffer s, int k) {
while (Integer.toString(temp).length() >= k) {
for (int i = 0; i < num2.length(); i++) {
StringBuffer s1 = new StringBuffer(num2);
String a = s1.deleteCharAt(i).toString();
int temp1 = Integer.parseInt(a);
if (temp > temp1) {
temp = Integer.parseInt(a);
}
}
StringBuffer ee = new StringBuffer(Integer.toString(temp));
if (ee.length() >= k) {
smaller(temp, k);
}
}
return temp;
}
static void smaller(int temp, int k) {
StringBuffer ee = new StringBuffer(Integer.toString(temp));
StringBuffer s1 = new StringBuffer(ee);
StringBuffer s2 = new StringBuffer(ee);
Integer temp1 = Integer.parseInt(s2.deleteCharAt(0).toString());
compute(ee, temp1, s1, k);
}
}
The infinite loop you are getting is because you are calling smaller() from inside compute() and compute() from inside smaller(). If this is done intentionally then also add a terminating condition , which would prevent it from looping infinitely.
You can use simple code as below :
import java.util.Arrays;
public class Delete3 {
public static void main(String[] args) {
int num = 246235789;
int numDigitRequired = 2;
System.out.println(getLeastNum(num, numDigitRequired));
}
static int getLeastNum(int num, int numDigitRequired) {
char[] a = (num + "").toCharArray();
Arrays.sort(a);
StringBuffer s = new StringBuffer();
for (int i = 0; i < numDigitRequired; i++)
s.append(Character.getNumericValue(a[i]));
return Integer.parseInt(s.toString());
}
}
I'm currently doing a simple university project about the arrays.
In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
setArray(in, num);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static void setArray(Scanner in, int[] num)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
num = new int[dim];
System.out.println("Size: " + num.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < num.length ; i++)
{
ran = (int) (Math.random() * var);
num[i] = ran;
System.out.println(num[i]);
}
}
Have a look at this question about whether Java is Pass By Reference
Your code would be better off like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
num = setArray(in);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static int[] setArray(Scanner in)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
int[] numToReturn = new int[dim];
System.out.println("Size: " + numToReturn.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < numToReturn.length ; i++)
{
ran = (int) (Math.random() * var);
numToReturn[i] = ran;
System.out.println(numToReturn[i]);
}
return numToReturn;
}
if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function .
The variable array num in the main function is different from that in setArray() function.