问题描述
有没有办法使用 JTextField 取多个不同的数字?
Is there any way to take several different numbers using JTextField?
例如,给出以下数值:2.0、3.0、4.0.我想分别把它们放到ArrayList中.
For example, following numeric values are given: 2.0, 3.0, 4.0. I would like to put them into ArrayList separately.
如何处理不正确的输入数据才能继续打字?
How to handle incorrect input data in order to continue the typing?
//in this case the resulst is "arList: 1.92239991"
textField = new JTextField("1.9, 223, 9991");
textField.addActionListener(this);
ArrayList<Double> arList = new ArrayList<>();
String str = textField.getText();
String result = str.replaceAll("\\s+","");
String otherResult = result.replaceAll(",","");
double d = Double.parseDouble(otherResult);
System.out.println(d);
arList.add(d);
for (Double anArList : arList) {
System.out.println("arList: " +anArList);
}
推荐答案
如果数字总是由 分隔,
你可以使用 String#split
,它会返回一个值数组.
If the numbers are always separated by ,
you can use String#split
, which will return an array of values.
String str = textField.getText();
String[] parts = str.split(",");
这将返回 ,
之间的每个值,包括空格.然后您可以修剪这些结果...
This will return each value between the ,
, including the white space. You could then trim these results...
for (int index = 0; index < parts.length; index++) {
parts[index] = parts[index].trim();
}
现在只包含剩余的文本.如果你必须把它放在一个列表中,你可以使用...
This will now contain just the remaining text. If you must have it in a list you can use...
List<String> values = Arrays.asList(parts);
如果您需要将它作为 Double
的列表,您将需要单独解析每个元素...
If you need it as list of Double
s, you will need to parse each element indiviudally...
List<Double> values = new ArrayList<Double>(parts.length);
for (String value : values) {
values.add(Double.parseDouble(value));
}
如果任何一个值不是有效的Double
,这仍然会抛出解析异常.
This will still throw a parse exception if any one of the values is not a valid Double
.
更好的解决方案可能是使用 JFormattedTextField
或 JSpinner
来收集单个值并将每个值一次添加到列表中(可以将它们显示在JList
),这将允许您在输入时验证每个值.
A better solution might be to use a JFormattedTextField
or JSpinner
to collect the individual value and add each one to a list one at a time (could display them in a JList
), this would allow you to validate each value as it is entered.
查看如何使用格式化文本字段、如何使用微调器 和 如何使用列表了解更多详情
Have a look at How to Use Formatted Text Fields, How to Use Spinners and How to Use Lists for more details
这篇关于JTextField - 数字分隔(ArrayList)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!