[英]How do I convert a BufferedReader-Input (String) to Integer and save it in an Integer List in java?
I would like to search for an Integer in a String given by a BufferedReader.我想在 BufferedReader 给出的字符串中搜索一个整数。 The Integers have to be saved inside an Integer-List and be returned.
整数必须保存在整数列表中并返回。 My Idea was splitting the String in a String [ ] and save the Integers with
Integer.parseInt
directly inside the Array-List, but unfortunatelly i only get NumberFormatExceptions, although the String [ ] is filled.我的想法是将字符串拆分为字符串 [] 并将整数与
Integer.parseInt
直接保存在数组列表中,但不幸的是我只得到 NumberFormatExceptions,尽管字符串 [] 已填充。 Could someone give me some advice?有人能给我一些建议吗?
public List<Integer> getIntList(BufferedReader br) {
List <Integer> List = new ArrayList<>();
try{
while(br.ready()){
try{
String line = (br.readLine());
String [] arr = line.split("\\s");
for (String s : arr) {
System.out.println(s);
}
if(line.equals("end")){
return List;
}
for (String s : arr) {
List.add(Integer.parseInt(s));
}
}
catch(IOException e){
System.err.println("IOException");
}
catch(NumberFormatException e){
System.out.println("Number");
}
}
return List;
}
catch(IOException e){
System.err.println("IOException");
}
return null;
}
You catch NumberFormatException in a wrong place so that you cannot continue number searching loop.您在错误的地方捕获了 NumberFormatException,因此您无法继续数字搜索循环。 You have to wrap this line
List.add(Integer.parseInt(s));
你必须包装这一行
List.add(Integer.parseInt(s));
into try catch block.进入 try catch 块。 Also never start variable name with capital letter.
也不要以大写字母开头变量名。
You can use following logic to check for a numeric string value.您可以使用以下逻辑来检查数字字符串值。
for(String s : arr){
if(s.chars().allMatch(Character::isDigit))
List.add(Integer.parseInt(s));
}
This way, you need not care about handling Number Format Exception.这样,您就不必关心处理数字格式异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.