我的弦乐索引如何超出界限?

时间:2016-02-09 03:09:13

标签: java string io java.util.scanner

目标:向用户询问点数。然后,用户将输入"1 4",其中1是x,4是y。我将分别获取子字符串1和4,然后将它们设为int,这样我就可以将它们设为Point

我一直在" java.lang.StringIndexOutOfBoundsException: String index out of range: -1" 这是在第25行,但不是24 。当我使用3而不是长度时,它也会给我这个错误。

这是代码片段:

public String run() { 
    String line = ""; 
    String first = ""; 
    String second = ""; 
    int j = 0; int n = 0;
    System.out.println("How many inputs do you want to enter?");
    Scanner sc = new Scanner(System.in);

    while(j == 0){

      if(sc.hasNextInt()){
        n = sc.nextInt();
        Point[] points = new Point[n];
        sc.close();
        j++;
      } 

      else {
        System.out.println("invalid input");
      }
    }

    Scanner scan = new Scanner(System.in);

    for(int i = 0; i <= n; i++){
      System.out.println("Enter x and y:");
      line = scan.next();
      first = line.substring(0,1);
      second = line.substring(2,line.length());      

    }

    scan.close();
    origin(points);

    return ""; 
}

1 个答案:

答案 0 :(得分:0)

看看这是否适合您。我不确定你的j变量在做什么,你的for-loop for the points超出了数组的界限,你在两个单独的System.in之间关闭Scanner,显然你的substring逻辑会发生错误。

此代码修复了所有这些问题并且对我来说非常有用。

public String run() {
    Scanner sc = new Scanner(System.in);

    int n = numberPrompt("How many inputs do you want to enter?\n", "Invalid input");
    Point[] points = new Point[n];

    for(int i = 0; i < n; i++){
        System.out.println("Enter x and y:");
        String line = sc.nextLine();
        String[] data = line.split("\\s+");
        if (data.length >= 2)
        {
            int x = Integer.parseInt(data[0]);
            int y = Integer.parseInt(data[1]);
            points[i] = new Point(x, y);
        }
    }

    System.out.println(Arrays.asList(points));

    origin(points);

    return "";
}

private int numberPrompt(String prompt, String error) {

    Integer number = null;
    boolean isValid;
    String input;
    Scanner sc = new Scanner(System.in);

    do {
        isValid = true; // reset the validity
        System.out.print(prompt);
        input = sc.nextLine();

        try {
            number = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            isValid = false;
            if (!(error == null || error.isEmpty())) {
                System.out.println(error);
            }
        }
    } while (!isValid);

    return number;
}