[英]Wrong work Scanner with String.charAt()
我在项目中使用扫描仪时遇到问题。 我有一个像这样的字符串文件:
我在数组中添加的所有此字符串,在此数组中添加了两个ArrayList。 我不需要以数字开头的女巫。 就像“ 1ip”。 所以我尝试跳过它。
那就是我的方法代码:
public void scan_file() throws IOException{
Scanner sc = null;
String [] array_string;
String not_sring;
try{
File out = new File("file.txt");
sc = new Scanner(out);
while(sc.hasNextLine()){
not_sring=sc.nextLine();
if(not_sring.charAt(0)>='0' && not_sring.charAt(0)<='9'){
array_string = sc.nextLine().split("=");
}
else{
array_string=sc.nextLine().split("=");
for (int i=0; i<array_string.length; i++)
for(int j=1; j<array_string.length; j++){
list_id.add(array_string[i]);
list_value.add(array_string[j]);
}
}
}
}
catch(FileNotFoundException e) {
//e.printStackTrace(System.out);
System.out.println("File not found");
scan_file();
}
sc.close();}
而且这一切都不起作用。 如果有人了解我的英语和我的任务。
您在循环中两次调用nextLine()
,这当然是您的问题之一。
如果要跳过一行,请继续执行下一个循环迭代:
if(not_sring.charAt(0)>='0' && not_sring.charAt(0)<='9'){
continue; // This will skip to the next while iteration begining with the conditional check
}
并且如果您的格式为id=value
不是use:
array_string=not_sring.split("="); // No need to use nextLine again as it will overwrite the current line read into not_sring
list_id.add(array_string[0]);
list_value.add(array_string[1]);
这是假设文件格式如上所述正确。 在这些模块之间不再需要else
模块。
try{
File out = new File("file.txt");
sc = new Scanner(out);
while(sc.hasNextLine()){
not_sring=sc.nextLine();
if(!Character.isDigit(not_sring.charAt(0))){
array_string = not_sring.split("=");
list_id.add(array_string[0]);
list_value.add(array_string[1]);
}
}
}
选中此选项,则不需要循环,如果需要阻塞,则需要一个循环,否则将丢弃该字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.