簡體   English   中英

String.charAt()工作掃描器錯誤

[英]Wrong work Scanner with String.charAt()

我在項目中使用掃描儀時遇到問題。 我有一個像這樣的字符串文件:

  • 名字= Jhon
  • 計數= 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();}

而且這一切都不起作用。 如果有人了解我的英語和我的任務。

您在循環中兩次調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM