【问题标题】:How is my String Index Out of Bounds?我的字符串索引如何越界?
【发布时间】:2016-02-09 03:09:13
【问题描述】:

目标:向用户询问点数。然后用户将输入"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 ""; 
}

【问题讨论】:

  • 您不需要声明多个Scanner
  • 不要closeScannerSystem.in那个 关闭System.in
  • 您的for loop 条件也可能是一个问题。不应该是for(int i = 0; i &lt; n; i++)吗??
  • 运行此代码,我在扫描仪上得到NoSuchElementException...可能是因为 System.in 已关闭

标签: java string io java.util.scanner


【解决方案1】:

看看这是否适合你。我不确定您的 j 变量在做什么,您的 for 循环点超出了数组的范围,您正在两个单独的 Scanners 之间关闭 System.in,显然发生了一些错误用你的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;
}

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 2011-12-13
    • 1970-01-01
    • 2019-08-01
    • 2016-06-10
    • 2013-12-08
    • 2014-10-16
    • 2019-02-18
    • 2017-03-22
    相关资源
    最近更新 更多