0

why does my code throws exception without taking a single input??

import java.util.*;
public class program3{
public static void main(String[] args) {
    System.out.println("Enter the number of elements in the array");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] arr = new int[n];

    try{
        System.out.println("Enter the elements in the array");
        for(int i=0;i<n;i++){
            String j = sc.nextLine();
            int k = Integer.parseInt(j);
            arr[i]=k;
        }

        System.out.println("Enter the index of the array element you want to access");
        int a = sc.nextInt();
        System.out.println("The array element at index "+a+" = "+arr[a]);
        System.out.println("The array element successfully accessed");
    }
    catch(ArrayIndexOutOfBoundsException e){
        System.out.println(e);
    }
    catch(NumberFormatException e){
        System.out.println(e);
    }
}
}

I need to generate NumberFormatException when I provide an input other than int. Instead, it is generated without taking any input.

This is the error message

Enter the number of elements in the array
2
Enter the elements in the array
java.lang.NumberFormatException: For input string: "" 
  • 1
    Did you use sc.nextInt() earlier in your code (maybe to accept the value of n)? The reason I ask is that a call to `sc.nextLine()` immediately after a call to one of `Scanner`'s `nextXXX()` methods (such as `nextInt()`, `nextDouble()`, `next()`, etc) might not work as you expect. Instead of waiting for you to type a line, it might instead immediately return a string of zero or more blanks without waiting for you to type. Is that what is happening to you? – Kevin Anderson Apr 19 '20 at 04:22
  • `String j = sc.nextLine(); if (j.matches("\\d+")) { int k = Integer.parseInt(j); arr[i]=k; } else { System.out.println("Nope! Try Again...."); }` – DevilsHnd Apr 19 '20 at 04:34

2 Answers2

-1

First, it would be nice to see full code and an exception stacktrace to understand what exactly line of code does throw it. Currently try block is not closed, so this code example is just not valid.

It might be int k = Integer.parseInt(j); It might be another line where you're reading n from input.

Second, could you try debugging and execute the code line-by-line to see exactly what is the String value and how it appeared?

Mikhail Kopylov
  • 1,767
  • 2
  • 21
  • 47
  • Good suggestion on seeing full code and stacktrace, but you're not answering the question, so this should have been written as a comment. As for last paragraph, the error message already shows exactly what `String` value is (an empty string), so no need for debugging to figure that out. – Andreas Apr 19 '20 at 04:41
  • The idea was to figure out how this empty string appeared - was it read from input sting or was it a default value, for example. And why this is not an answer to the question? – Mikhail Kopylov Apr 19 '20 at 04:43
  • The empty string appeared in the previous line with the call to `nextLine()`, that seems pretty obvious. --- 1st paragraph: "we need full code and stacktrace". That's a good comment, not an answer. --- 2nd paragraph: "it might be `parseInt` or some other line". Not very helpful and it's a comment, not an answer. --- 3rd paragraph: "try debugging". That's a good comment, not an answer. --- In short, this "answer" is a comment, not an answer. – Andreas Apr 19 '20 at 04:56
  • Ok, I got the idea, than's for your clarification. The only thing - empty string reason is not so obvious since `n` is not defined. So there may be a `NumberFormatException` while reading `n` and `int k = Integer.parseInt(j);` is not executed at all. That seems more real for me. – Mikhail Kopylov Apr 19 '20 at 05:07
  • 1
    Maybe, but I guess you haven't seen how often we get questions about `nextLine()` returning empty string because it was preceded by a `nextInt()` (or similar) call, so the probability that OP showed *this* code because this is where the error occurred and was caused by `nextInt()` before the loop, is a lot higher than probability of OP showing the wrong code (which admittedly has happened too, but probability is extremely low here). – Andreas Apr 19 '20 at 05:14
-1

May be this is what you are trying to do., By doing it this way, you will be able to figure out, which input caused the problem for you.

   try
    {
        Scanner sc = new Scanner( System.in );
        System.out.println( "Enter the size of the array : " );
        String userInputValue = sc.nextLine().strip();
        System.out.println( "Your input for arraySize is : " + userInputValue );

        if( userInputValue.isBlank() )
        {
            throw new NumberFormatException( "Empty value cannot be added as array size" );
        }

        int n = Integer.parseInt( userInputValue.strip() );  // size of the array, this also will be the size of the input from user
        int[] arr = new int[n];
        System.out.println( "Enter the elements in the array" );
        for( int i = 0; i < n; i++ )
        {
            String j = sc.nextLine();
            if( j.isBlank() )
            {
                throw new NumberFormatException( "Empty value cannot be added as array element " );
            }
            int k = Integer.parseInt( j.strip() ); // Strip added to remove possible leading and trailing whitespaces from user input
            arr[i] = k;
        }

        System.out.println( "Elements you entered are : " );
        for( int i : arr )
        {
            System.out.print( i + " " );
        }
    }
    catch( NumberFormatException e )
    {
        System.out.println( "Input value is not valid : " + e.getMessage() );
    }
Klaus
  • 1,429
  • 7
  • 16
  • You sure don't want to create `Scanner` inside the loop, and the question code very likely asks the user for `n`, which is extremely likely the cause of the problem. Besides, the error in the question clearly shows an attempt at parsing an empty string as a number, so calling `strip()` is certainly not going to fix that. – Andreas Apr 19 '20 at 04:36
  • @Andreas I've updated my answer. Thanks for pointing out that `Scanner` inside the loop – Klaus Apr 19 '20 at 04:47
  • So what exactly did you do to fix the problem? There is no description. --- I know, you replaced the `nextInt()` we can't see in the question with a `nextLine()`, right? Well, that just makes this answer a duplicate of the answers in the linked question up top. – Andreas Apr 19 '20 at 05:00