0

我在项目中使用 Scanner 时遇到问题。我有一个带有这样字符串的文件:

  • 姓名 = 乔恩
  • 计数 = 100
  • 1ip = 127.0.0.7
  • 结束=文件

我将所有这些字符串添加到数组中,并且该数组添加到两个 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();}

而这一切都行不通。如果有人理解我的英语和我的任务。

4

3 回答 3

1

您在循环中调用了两次nextLine(),这当然是您的问题之一。

于 2013-04-15T11:39:33.333 回答
0

如果你想跳过一行,只需继续下一个循环迭代:

 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不是使用:

    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这些块之间不再需要了。

于 2013-04-15T11:41:30.937 回答
0
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]);
              }
          }

}

检查这个,你不需要循环,你需要一个 if 块,否则字符串将被丢弃。

于 2013-04-15T11:56:22.860 回答