pty115 pty115 - 1 month ago 5
Java Question

Java abruptly terminates when hasNextInt() encountered the end of input

I'm trying to make stack. I used debug tool in Eclipse, and found the code terminates when

hasNextInt()
encountered the end of input. the below code terminates at 14th while loop, and 18th statement of the code
if(sc.hasNextInt()) {
. I also thought about JVM memory, but this code is not recursive, and the size of array is only 20!...

Here is input, I copy and pasted it to console (last "top" doesn't operate..) >>

14 push 1 push 2 top size empty pop pop pop size empty pop push 3 empty top


Here is the code>>

import java.util.Scanner;
public class User_Stack {
final static int SIZE = 20;
static int[] array = new int[SIZE];
static int where = -1;

public static void main(String[] args) {
String test; int input=0, result=0, tc=1;
Scanner sc = new Scanner(System.in);

/*input the number of test cases*/
int test_case = sc.nextInt();

while(tc <= test_case){
/*input what will do with Stack by String*/
test = sc.next();
/*what is pushed is input by Integer*/
if(sc.hasNextInt()) {
input=sc.nextInt();
}
/*call function by test String*/
switch(test){
case "push":
push(array, input);
break;
case "pop":
System.out.println(pop(array));
break;
case "size":
System.out.println(size(array));
break;
case "empty":
System.out.println(empty(array));
break;
case "top":
System.out.println(top(array));
break;
}
}

}

public static void push(int[] array, int x){
if(where+1==SIZE) return;
array[++where]=x;
}
public static int pop(int[] array){
if(where==-1) return array[where--];
else return -1;
}
public static int size(int[] array){
return where+1;
}
public static int empty(int[] array){
if(where==-1) return 1;
else return 0;
}
public static int top(int[] array){
if(where==-1) return array[where];
else return -1;
}
}

Answer

This is because the Scanner waits for the next input token to know whether it is an integer or not and as it reached the end of your input, it waits for ever. You should move sc.nextInt() directly into the push as next:

while(tc <= test_case){
    /*input what will do with Stack by String*/
    test = sc.next();

    /*call function by test String*/
    switch(test){
        case "push":
            push(array, sc.nextInt());
            break;
        case "pop":
            System.out.println(pop(array));
            break;
        case "size":
            System.out.println(size(array));
            break;
        case "empty":
            System.out.println(empty(array));
            break;
        case "top":
            System.out.println(top(array));
            break;
    }
}
Comments