0

When i run the following program I get an error at line 20, and this is my code:

package J1;
import java.util.Scanner;

public class SpeedLimit {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int input = keyboard.nextInt();

    String[] tab = new String[2];
    String output="";
    int speed = 0;
    while(input!=-1){
        int last =0;
        for (int i=0; i<input ; i++){

            String pair = keyboard.next();

            tab = pair.split(" ");
            speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
            last = Integer.parseInt(tab[1]);
        }
        output = output +speed + "miles" + "\n";
        speed =0;
     input = Integer.parseInt(keyboard.nextLine());
    }
   System.out.println(output);
}

}

when i run the code, I enter the following input from the keyboard:

 3
 20 2
 30 6
 10 7
 2
 60 1
 30 5
 4
 15 1
 25 2
 30 3
 10 5
 -1

to get this result as an output: 170 miles 180 miles 90 miles

but i get the following Error when i run the code

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
Med Ada
  • 55
  • 8
  • 1
    `String pair = keyboard.nextLine();` – Sanket Makani May 05 '17 at 17:15
  • i dont understand – Med Ada May 05 '17 at 17:17
  • In the line `String pair = keyboard.next();` the `.next()` returns "the next complete token from this scanner." I think that @SanketMakani is suggesting that it might be returning only the first word instead of the whole line. If you replace the line with the one suggested, it will fetch the whole line. – dolan May 05 '17 at 17:20

5 Answers5

2

String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".

Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.

while(input!=-1){
    int last =0;
    for (int i=0; i<input ; i++){

        int ip1=keyboard.nextInt();
        int ip2=keyboard.nextInt();

        speed = speed + ip1*(ip2-last);
        last = ip2;
    }
    output = output +speed + "miles" + "\n";
    speed =0;
 input = keyboard.nextInt();
}
Sanket Makani
  • 2,491
  • 2
  • 15
  • 23
  • it get the same problem when i type 4 in the execution ` 4 ` and give me this Error `Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at J1.SpeedLimit.main(SpeedLimit.java:21) ` – Med Ada May 05 '17 at 17:30
  • Works perfectly on my machine. I will update the code try that code! – Sanket Makani May 05 '17 at 17:32
  • with the use of token1 and token 2 i got another Error when i type `10 7` AND this is the Error : `Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at J1.SpeedLimit.main(SpeedLimit.java:27)` – Med Ada May 05 '17 at 17:41
  • @MedAda, Its almost impossible to get this error while getting inputs.You have surely made other mistakes But now leave all this and take input directly in the integer. Check edited code. – Sanket Makani May 05 '17 at 17:44
  • can you explain to me how Scanner work, and the difference between .next() and .nextLine() ? – Med Ada May 05 '17 at 17:51
  • Refer this [answer](http://stackoverflow.com/questions/32798803/understanding-scanners-nextline-next-and-nextint-methods). – Sanket Makani May 05 '17 at 17:52
0

You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.

*nextLine(): reads the remainder of the current line even if it is empty.

        keyboard.nextLine(); //To avoid the exception you commented
        String pair = keyboard.nextLine(); //here is solved
        tab = pair.split(" ");
Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34
  • But when I try nextLine() instead of next(), I got this Error: `Exception in thread "main" java.lang.NumberFormatException: For input string: ""at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at J1.SpeedLimit.main(SpeedLimit.java:20)` – Med Ada May 05 '17 at 17:22
  • Ah you should do keyboard.nextLine(); when you start looping to eat the enter key. – Oussama Ben Ghorbel May 05 '17 at 17:25
0

Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.

SajeeshR
  • 21
  • 2
0

You Can try below changes in your code :

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    int input = Integer.parseInt(keyboard.nextLine());

    String[] tab = new String[2];
    String output="";
    int speed = 0;
    while(input!=-1){
        int last =0;            
        for (int i=0; i<input ; i++){
            String pair = keyboard.nextLine();              
            tab = pair.split(" ");
            speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
            last = Integer.parseInt(tab[1]);
        }
        output = output +speed + " miles " + "\n";
        speed =0;
     input = Integer.parseInt(keyboard.nextLine());
    }
   System.out.println(output);
}
Nishesh Pratap Singh
  • 2,131
  • 2
  • 13
  • 20
0

i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.

try adding an check for the length of tab before executing your line 20.

this should do the trick:

if(tab.length() > 1){

  speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);

} 
AppleCiderGuy
  • 1,249
  • 1
  • 9
  • 16
  • i want to excute this line : `speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);` i dont want to skip it – Med Ada May 05 '17 at 17:43