使用String.charAt()的错误工作Scanner

时间:2013-04-15 11:33:52

标签: java file

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

  • 姓名= Jhon
  • count = 100
  • 1ip = 127.0.0.7
  • end = file

我在数组中添加所有这个字符串,这个数组添加在两个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();}

这一切都没有用。如果有人理解我的英语和我的任务。

3 个答案:

答案 0 :(得分:1)

你在循环中调用两次nextLine(),这肯定是你的问题之一。

答案 1 :(得分: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

答案 2 :(得分: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块,否则字符串将被丢弃。