gpt4 book ai didi

java.lang.ArrayIndexOutOfBoundsException 和 If 逗号后面的条目不是整数

转载 作者:太空宇宙 更新时间:2023-11-04 12:26:15 25 4
gpt4 key购买 nike

我的代码中不断收到错误:java.lang.ArrayIndexOutOfBoundsException: 1。这是我学习 java 的第一个学期,所以任何帮助将不胜感激。还有,一石二鸟。我的 if 语句之一遇到问题。

如果逗号后面的条目不是整数:

输出:“错误:逗号后面没有跟整数。”

提前致谢。

import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.StringWriter;

public class DataVisualizer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner inSS = null;
String title = "";
String column1header = "";
String column2header = "";
String dataString = "";
String dataPoint = "";
String dataInt = "";
boolean inputDone = false;
char comma = ',';

System.out.println("Enter a title for the data: ");
title = input.nextLine();

System.out.println("You entered: " + title);
System.out.println("");

System.out.println("Enter the column 1 header: ");
column1header = input.nextLine();

System.out.println("You entered: " + column1header);
System.out.println("");

System.out.println("Enter the column 2 header: ");
column2header = input.nextLine();

System.out.println("You entered: " + column2header);
System.out.println("");

ArrayList<String> string = new ArrayList<String>();
ArrayList<Integer> integer = new ArrayList<Integer>();

System.out.println("Enter a data point (-1 to stop input): ");

while (!inputDone) {

dataPoint = input.nextLine();
inSS = new Scanner(dataPoint);

if (dataPoint.equals("-1")) {
inputDone = true;
break;
}

if (!dataPoint.contains(",")) {
System.out.println("Error: No comma in string.");

}

// Here is the problem I am running with my if statement.

if (dataPoint.indexOf(",") != dataPoint.lastIndexOf(",")) {
System.out.println("Error: Too many commas in input.");

}

if (Character.isDigit(dataPoint.charAt(-1))) {
System.out.println("Error: Comma not followed by an integer.");
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");
}


else {

// This is where Im getting my error

String[] items = dataPoint.split(",");

for (int i = 0; i < items.length; ++i){
dataString = items[0];
dataInt = items[1];
}

Integer dataInteger = Integer.valueOf(dataInt);
System.out.println("Data string: " + dataString);

System.out.println("Data integer: " + dataInteger);

string.add(dataString);
integer.add(dataInteger);
}
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");

}
return;
}
}

最佳答案

您试图获取索引-1处的字符,在这里您将得到StringIndexOutOfBoundsException

Character.isDigit(dataPoint.charAt(-1))

索引应该在0到string.length()-1之间

关于java.lang.ArrayIndexOutOfBoundsException 和 If 逗号后面的条目不是整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com