javaarraysexceptionerror-handlingjava.util.scanner

NoSuchElementException and premature closure of scanner


I have made a program that reads 5 integers and outputs its polarity(positive or negative), its type(odd or even). Used Scanner.nextLine() to read the input as string and split it with .split("\s+") and phrased every entry into an integer in a for loop. For error handling when I tried to enter an non integer input such as a character the scanner.nextLine() gets closed prematurely and throws a NoSuchElementException.

Here's my full code:

import java.util.Scanner;

public class Checker {
    public static class outputVal{
        private String polarity, type;

        public outputVal(String x, String y){
            this.polarity = x;
            this.type = y;
        }
        public String getPolarity() {
            return polarity;
        }
        public String getType() {
            return type;
        }
    }
    public static int[] getInput(){
        Scanner scanner = new Scanner(System.in);
        try{
            String input = scanner.nextLine();
            String [] inputTokens  = input.split("\\s+");
            int [] intTokens  = new int[5];
            for(int i=0; i<inputTokens.length; i++){
                intTokens[i] = Integer.parseInt(inputTokens[i]);
            }
        return intTokens;
        }
        catch(NumberFormatException e){
            System.out.println("[ERROR] Enter only integer!!!");
            return new int[0];
        }
        finally{
            scanner.close();
        }
        
    }

    public static String checkPolarity(int x){
        if(x== 0){
            return "Zero";}
        else{
        return x>0 ? "Positive" : "Negative";
        }   
    }

    public static String evenOdd(int x){
        return x%2 ==0 ? "Even" : "Odd";  
    }   

    public static String checkValue(int[] x){
        if(x.length <2) return "N/A";
        if(x[0]==x[(x.length)-1]){
            return "Equal";}
        else{
        return x[0]>x[(x.length)-1] ? "Greater" : "Lesser";
        }   
    }
    
    public static void main(String[] args) {
        int[] input = new int[5];

        while(input.length == 0){
            System.out.print("Enter five integers: ");
            input = getInput();
            if(input.length == 0 )System.out.println("[ERROR] Inappropriate Data. Please try again.");
        }
        
        if(input.length<5) {
            System.err.println("[ERROR] Insufficient Data. Exitting....");
            return;
        }

        outputVal[] output = new outputVal[input.length];

        for(int i= 0; i<input.length; i++){
            output[i] = new outputVal(checkPolarity(input[i]),evenOdd(input[i])); 
        }

        for(int i= 0; i<input.length; i++){
            System.out.printf("The number '%d' is %s, %s %n",input[i],output[i].getPolarity(),output[i].getType());
        }

        System.out.printf("%nThe first number is %s than the last number", checkValue(input));
    }
}

....................


Solution

  • Your code has two small problems:

    This is solved by putting the instantiation in the start method (formerly main), as well as the call to close().

    public int[] getInput() {
       try {
          String input = scanner.nextLine();
          String[] inputTokens = input.split( "\\s+" );
          int[] intTokens = new int[ 5 ];
          for( int i = 0; i < inputTokens.length; i ++ ) {
             intTokens[ i ] = Integer.parseInt( inputTokens[ i ] );
          }
          return intTokens;
       }
       catch( NumberFormatException e ) {
          System.out.println( "[ERROR] Enter only integer!!!" );
          return new int[ 0 ];
       }
    }
    
    public void start() {
       int[] input = new int[0]; 
       while(input.length == 0 ){
          System.out.print( "Enter five integers: " );
          input = getInput();
          if( input.length == 0 ) {
             System.out.println( "[ERROR] Inappropriate Data. Please try again." );
          } 
       }
    
       if( input.length < 5 ) {
          System.err.println( "[ERROR] Insufficient Data. Exitting...." );
          return;
       }
    
       outputVal[] output = new outputVal[ input.length ];
    
       for( int i = 0; i < input.length; i ++ ) {
          output[ i ] = new outputVal( checkPolarity( input[ i ] ), evenOdd( input[ i ] ) );
       }
    
       for( int i = 0; i < input.length; i ++ ) {
          System.out.printf( "The number '%d' is %s, %s %n", input[ i ], output[ i ].getPolarity(), output[ i ].getType() );
       }
    
       System.out.printf( "%nThe first number is %s than the last number", checkValue( input ) );
       scanner.close();
    }
    
    public static void main( String[] args ) {
       new Checker().start();
    }