0

I am new to java and I am still getting used to most of the syntax. Here I tried to get two inputs (the first one being an int and the second one a string) and later one I do some calculations with them. But when I run the program, it gives this message:

Exception in thread "main" java.lan._NumberFormatException: For input string: "" 
at java.lang.NumberFormatException.forInputString(NuthberFormatException.java:65) 
at java.lang.Integer.parseInt(Integer.java:592) 
at java.lang.Integer.parseInt(Integer.java:615) 
at Main.main(Main.java:13) 

.

import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static void main(String args[]) {
        Scanner myObj = new Scanner(System.in);
        int N = myObj.nextInt();
        String Input = myObj.nextLine();
        String[] Inputs = Input.split(" ", 0);
        int size = Inputs.length;
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = Integer.parseInt(Inputs[i]);
        }
    }
}

My understanding is that the program is assuming both inputs as the same. But how do I fix that?

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
RicardoMM
  • 133
  • 8
  • Can you share an example input that produces this error? – Mureinik Apr 11 '20 at 11:37
  • I would normaly try to input something like 3 and in the next line 1 2 6. But it gives error after i input the first number. Even using console it gives the same error. – RicardoMM Apr 11 '20 at 11:38
  • @Kevin Anderson It does, thank you! I didnt understand that the problem was that it wasn't inputing anything as a String – RicardoMM Apr 11 '20 at 11:40
  • An extra `.nextLine()` (which basically reads an empty rest-of-the-line) after using `.nextInt()` will solve it. – Kevin Anderson Apr 11 '20 at 11:42
  • @KevinAnderson - please open the question if you can. Note that OP is already using `nextLine()`. I know why OP is facing the problem but the answer won't fit into a comment. I missed submitting my answer by less than a second. – Arvind Kumar Avinash Apr 11 '20 at 11:50
  • @ArvindKumarAvinash I can't reopen the question unilaterally, but I've cast my vote in favor... – Kevin Anderson Apr 11 '20 at 12:02
  • Thanks, @KevinAnderson for the vote. Hopefully, it will be opened. – Arvind Kumar Avinash Apr 11 '20 at 12:05
  • @RicardoMM - I hope the solution worked for you. Do not forget to accept the answer so that future visitors can also use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash May 17 '20 at 17:03

0 Answers0