【发布时间】:2020-07-09 03:59:33
【问题描述】:
当我单击“添加”按钮时,我正在尝试将文本字段中的用户输入添加到数组中。显示按钮显示整个数组。我已经在程序的其他位置初始化了数组 (array = new String[10])。我将计数器初始化为 0 作为私有变量。如果用户输入的字符串超过 10 个,则不应添加输入。有什么建议吗?
// if add button is clicked
if (e.getSource() == btnAdd){
/*input = textInput.getText();
output = textOutput.getText() + input + "\n";
textOutput.setText(output);*/
// get user input from text field
input = textInput.getText();
// clear text input field
textInput.setText("");
/*do {
array[counter] = input;
counter++;
} while (counter < 11);
if (counter > 10){
picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
picBottom.setC(Color.RED);
}*/
// add user input to array if counter is within array length
if (counter <= 10){
array[counter] = input;
counter++;
}
// display no more space available if counter is outside of array length
else {
picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
picBottom.setC(Color.RED);
}
}
// if display button is clicked
else if (e.getSource() == btnDisplay){
// go through array & display each string
for (int i = 0; i <= counter; i++){
output += array[i];
textOutput.setText(output);
}
}
【问题讨论】:
-
array = textfield.getText().toCharArray();呢? -
数组为String数组
-
还有什么问题?发布的代码看起来很合理。您是否在 if 语句中添加了任何调试代码以查看代码是否已执行?
-
当我输入超过 10 个输入时,控制台屏幕上会弹出错误。我相信当单击添加按钮时,错误出现在 if else 语句中。如果输入少于 10 个,则显示按钮在数组前后显示“null”。
-
counter 从 0 开始计数。所以你有变化:
if (counter <= 10)到if (counter < 10)所以 counter 只能是 0, 1, ....8, 9 就像你定义的数组一样。跨度>
标签: java arrays swing jtextfield