0

I am new to programming, so just consider my mistakes. I am writing a program where the user gives two input numbers in one line separated by whitespace. I have to assign the first input to an integer variable and second to a double and have to perform some mathematics and show the result. Following is my code:

import java.util.Scanner;
public class foo{
    public static void main(String[] args){
        String b = null;
        Scanner sc = new Scanner(System.in);
        b = sc.next();
        String[] split = b.split(" ");
        int i = Integer.parseInt(split[0]);
        double d = Double.parseDouble(split[1]);
        System.out.println(i+20);
        System.out.println(d-1.50);
    }
}    

And following is the error i am getting while running it.

F:\java\work\codechef>javac foo.java

F:\java\work\codechef>java foo
20 300.50
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at foo.main(foo.java:9)

First I tried making it with b=sc.readLine(); but there i got the following error while compiling:

error: cannot find symbol
                b = sc.readLine();
                      ^
  symbol:   method readLine()
  location: variable sc of type Scanner
1 error

Why I am getting these errors and how to solve the above problem.

  • 3
    use `sc.nextLine` instead of `sc.next` – Zircon Jun 29 '16 at 20:12
  • @Tunaki This is not a duplicate, the problem is different, although it throws ArrayIndexOutOfBoundsException – Krzysztof Krasoń Jun 30 '16 at 04:34
  • @krzyk The problem is the same: an attempt is made to access the index of an array that was out of bounds. It is understanding this error that leads to the solution, namely, why `split[1]` is throw the exception, so why `b.split(" ")` returned an array of length 1, so why `next()` only had 1 space. The OP could also refer to http://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class. – Tunaki Jun 30 '16 at 07:28
  • @Tunaki you could say the same for NPE, and all other exceptions from JDK. But there is wide area of problems that can result in those exceptions, throwing all into a strict number of already answered questions doesn't help – Krzysztof Krasoń Jun 30 '16 at 08:49

1 Answers1

1

You used sc.next() which returns the next token (a token is something that had delimiter before and/or after) so it contains only the 20 or 300.50 in your case.

You should use sc.nextLine() to use split later on, this will return the full line.

Or use:

int i = Integer.parseInt(sc.next());
double d = Double.parseDouble(sc.next());

And get rid of lines:

    b = sc.next();
    String[] split = b.split(" ");
Krzysztof Krasoń
  • 23,505
  • 14
  • 77
  • 102