0

I got Java ArrayIndexOutOfBoundsException when getting String input in Java. Please help me. This is my code: I edited my code to split using : it says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at solution2.Solution.main(Solution.java:27) "

import java.util.Scanner;

public class Solution {

public static void main(String[] args){

    Scanner scan = new Scanner(System.in);
    String str = scan.next();
    String strarr[] = str.split(",");
    String temp = strarr[0];
    String temparr[] = temp.split(".");
    String temp1 = strarr[1];
    String temparr1[] = temp.split(".");
    int x1 = Integer.parseInt(temparr[0]);
    int x2 = Integer.parseInt(temparr[1]);
    int y1 = Integer.parseInt(temparr1[0]);
    int y2 = Integer.parseInt(temparr1[1]);
    System.out.println(distance(x2,x1,y2,y1));

}

public static int distance(int x1,int y1,int x2,int y2){

    int xlen=x2-x1;
    int ylen=y2-y1;

    return (xlen+ylen)*10-(ylen*5);     

}

}

4

2 に答える 2

0

You need to escape the dot character in the String.split() regex, otherwise any character will be matched:

String temparr[] = temp.split("\\.");

For temparr1, I think you meant to use temp1:

String temparr1[] = temp1.split("\\.");

If you are expecting double values you could use Scanner.nextDouble() instead.

于 2012-10-20T12:57:56.680 に答える
0

Did you notice that you are assigning temp.split() to temparr1 instead of temp1.split()?

Also, split takes in a regular expression as an argument, and as it happens, the regexp . matches just about anything. So, you should correct that.

I assume, from lack of anything disproving my guess, that you are parsing an input of format 1.2,3.4, where 1,2,3, and 4 are arbitrary numbers.

Beside that, Scanner.next reads in the next token, meaning that it will read only "1" from "1.2,3.4". You have to use Scanner.nextLine.

于 2012-10-20T12:58:29.333 に答える