1

我有一个非常简单的程序,带有一个文本框和一个按钮。

用户被告知在框中输入两种颜色的名称,并用空格分隔。

例如“red green” 输出将在屏幕上打印,“The apple is red with green dots.”。

但是,当屏幕上只输入一个单词时,我需要它起作用。我正在使用一个包含拆分字符串的数组。当我只输入红色时,我收到此错误。

“AWT-EventQueue-0”java.lang.ArrayIndexOutOfBoundsException:

这是代码:

String userInput = textField.getText();
String[] userInputSplit = userInput.split(" ");
String wordOne = userInputSplit[0];
String wordTwo = userInputSplit[1];
if (wordTwo !=null){
                System.out.println("The apple is " + wordOne + " with " + wordTwo + " dots.");
                } else {
                 System.out.println("The apple is " + wordOne + " with no colored dots.");
                }
4

3 回答 3

2

可以像这样简单地做一些事情:

String wordOne = userInputSplit[0];
String wordTwo = null;
if (userInputSplit.length > 1){
    //This line will throw an error if you try to access something 
    //outside the bounds of the array
    wordTwo = userInputSplit[1];  
}
if (wordTwo !=null) {
    System.out.println("The apple is " + wordOne + " with " + wordTwo + " dots.");
} 
else {
    System.out.println("The apple is " + wordOne + " with no colored dots.");
}
于 2012-11-15T23:41:44.677 回答
2

您可以使用保护if语句括起您的打印逻辑:

if (userInputSplit.length > 1) {
  String wordOne = userInputSplit[0];
  String wordTwo = userInputSplit[1];
  ...
}
于 2012-11-15T23:41:53.197 回答
2

您还可以进行前置条件检查以查看用户的输入是否包含任何空格...

String userInput = textField.getText();
userInput = userInput.trim(); // Remove any leading/trailing spaces
if (userInput != null && userInput.length() > 0) {
    StringBuilder msg = new StringBuilder(64);
    if (userInput.contains(" ")) {
        String[] userInputSplit = userInput.split(" ");
        String wordOne = userInputSplit[0];
        String wordTwo = userInputSplit[1];
        msg.append("The apple is ").append(wordOne);
        msg.append(" with ").append(wordTwo).append(" dots");
    } else {
        msg.append("The apple is ").append(userInput).append(" with no colored dots.");
    }
    System.out.println(msg);
} else {
    // No input condition...
}

这只是看待问题的另一种方式......

于 2012-11-15T23:56:26.390 回答