2014-10-19 53 views
1

如何使用掃描儀取出奇數行並按順序放置它們?如何使用掃描儀取出奇數行並按順序放置它們?

的問題是,我有一個文本文件,看起來像這樣:

case0: 
a1: 
    0 
a2: 
    0 
a3: 
    0 
a4: 
    0 
a5: 
    0 
a6: 
    0 
a7: 
    1 
a8: 
    0 
a9: 
    0 

我需要讓輸出如:

caseNumber :0 
case content :000000100 

怎麼辦呢?

這裏是一個版本,香港專業教育學院寫到目前爲止,你可能想添加一些對:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class FileScanner { 

    File f = new File("test.txt"); 

    public static void main(String[] args) { 
     FileScanner fs = new FileScanner(); 

     fs.readfile(); 

    } 

    public void readfile() { 

     try { 

      // create a new scanner with the specified String Object 
      Scanner scanner = new Scanner(f); 

      int lineCount = 0; 
      while (scanner.hasNextLine()) { 
       lineCount++; 
       String line = scanner.nextLine(); 
       // System.out.println("Line :" + line); 
       String line1 = line.trim(); 
       // System.out.println(line1); 

       for (lineCount = 0; lineCount<19; lineCount++) { 



        line1 = line1.substring(line1.lastIndexOf("e") + 1); 
        // System.out.println("what is here :"+line1); 
        line1 = line1.substring(0, line1.lastIndexOf(":")); 


        int caseNum = Integer.parseInt(line1); 
        System.out.println("caseNumber :" + caseNum); 





       }; 

       // System.out.println(""+line1); 
       // int caseNumber = Integer.parseInt(line1); 
       // System.out.println("caseNumber :" + caseNumber); 
      } 

      System.out.println("line count" + lineCount); 
     } catch (FileNotFoundException e) { 

     } 
     // find the next token and print it 
     // System.out.println("" + scanner.next()); 

     // find the next token and print it 
     // System.out.println("" + scanner.next()); 

     // close the scanner 
    } 
} 

Contious最後一個問題.. 權,我得到這樣的輸出:

Case Number: -1 
Case Contents: 000000100 
Line Count: 4085 

我認爲案件號碼有點不對。

然後,我就215套的情況下(在同一文件和相同的格式與第一組數據),我需要做的輸出,如:

Case Number: 0 
Case Contents: 000000100 

Case Number: 1 
Case Contents: 000000101 

Case Number: 2 
Case Contents: 000010101 
. 
. 
.(showing all the cases) 
Line Count: 4085 

回答

2

首先,添加一個方法到類確定一個字符串是否是數字:

private boolean isNumeric(String number) 
{ 
    try 
    { 
     Integer.parseInt(number); 
     return true; 
    } 
    catch(NumberFormatException e) 
    { 
     return false; 
    } 
} 

這種方法的工作方式是,我們試圖將String解析爲一個int,如果失敗,因爲我們正在使用try/catch語句,我們可以防止程序拋出錯誤,而只是return false;。如果沒有失敗,它會繼續到return true;

現在,我們已經確定的方式是什麼的不是數字,我們可以返工while循環利用新方法的優點:

Scanner scanner = new Scanner(f); 

int lineCount = 0; 
int caseNumber = -1; 
String contents = ""; 
while(scanner.hasNextLine()) 
{ 
    lineCount++; 
    String line = scanner.nextLine().trim(); 
    if(lineCount == 1) 
    { 
     if(line.startsWith("case")) 
     { 
      String subStr = line.substring(line.indexOf("e") + 1, 
       line.indexOf(":")); 
      if(isNumeric(subStr)) 
       caseNumber = Integer.parseInt(subStr); 
     } 
    } 
    else if(isNumeric(line)) 
     contents += line; 
} 

scanner.close(); 

System.out.println("Case Number: " + caseNumber); 
System.out.println("Case Contents: " + contents); 
System.out.println("Line Count: " + lineCount); 

這是我改變了:首先,我添加了一個新的來表示案例編號。然後我添加了一個新的String contents來表示案件的內容。接下來,我改變了:

String line = scanner.nextLine(); 

String line = scanner.nextLine().trim(); 

,並擺脫了其他String line1 = line.trim();的,因爲沒有任何理由來創建兩個新的變量時,我們可以只在一個一舉兩得的操作。

接下來,我添加了一個if語句以查看我們是否在第一行,以便我們可以確定案例編號。如果該行以"case"開頭,則我們從e:的子字符串,表示爲subStr,以獲得案例編號。通過我們的isNumeric方法運行subStr,我們可以確定案例號是否可以被解析爲int。如果返回true,我們設置caseNumber等於Integer.parseInt(subStr)這將把字符串轉換爲int。

然後我添加了一個else語句來處理第一行之後的所有行。對於這些行中的每一行,我們所要做的就是確定該行是否是使用isNumeric的數字。如果它是數字,我們使用+=運算符將它附加到contents的末尾。如果不是,我們跳過它。

最後,我確保通過執行scanner.close()關閉掃描儀,以便我們沒有資源泄漏。

然後你走了!我希望你能理解並學習所有的改變。下面是該程序的輸出:

Case Number: 0 
Case Contents: 000000100 
Line Count: 19 

要回答你的後續問題:

這裏是while循環,讓您打印出多個案例及其內容:

Scanner scanner = new Scanner(f); 

int lineCount = 0; 
int caseNumber = -1; 
String contents = ""; 
while(scanner.hasNextLine()) 
{ 
    lineCount++; 
    String line = scanner.nextLine().trim(); 
    if(line.startsWith("case")) 
    { 
     if(!contents.isEmpty()) 
     { 
      System.out.println("Case Number: " + caseNumber); 
      System.out.println("Case Contents: " + contents); 
      caseNumber = -1; 
      contents = ""; 
     } 
     String subStr = line.substring(line.indexOf("e") + 1, 
       line.indexOf(":")); 
     if(isNumeric(subStr)) 
      caseNumber = Integer.parseInt(subStr); 
    } 
    else if(isNumeric(line)) 
     contents += line; 
} 

scanner.close(); 

System.out.println("Case Number: " + caseNumber); 
System.out.println("Case Contents: " + contents); 
System.out.println("Line Count: " + lineCount); 

以下是我從以前的答案改變,使其工作:

第一我刪除了if語句,該語句檢查lineCount == 1,並將else語句附加到第二個if語句的末尾,以檢查該行是否以「case」開頭。

所以,換句話說,這樣的:

if(lineCount == 1) 
{ 
    if(line.startsWith("case")) 
    { 
     ... 
    } 
} 
else if(isNumeric(line)) 
    ... 

成爲本:

if(line.startsWith("case")) 
{ 
    ... 
} 
else if(isNumeric(line)) 
    ... 

接下來,我添加了if(line.startsWith("case"))語句來檢查,如果我們在一個新的案例中一個新的if語句或不。基本上它所做的是檢查contents字符串是否爲空。如果是這樣,我們在案例0。如果不是,我們的案例大於0。如果聲明是真實的,我們打印出來的情況下,數量和內容,然後重新設置兩個變量的值,因此它們可以再次使用:

if(!contents.isEmpty()) 
{ 
    System.out.println("Case Number: " + caseNumber); 
    System.out.println("Case Contents: " + contents); 
    caseNumber = -1; 
    contents = ""; 
} 

就是這樣!真!

這裏是輸出:

Case Number: 0 
Case Contents: 000000100 
Case Number: 1 
Case Contents: 101001001 
Line Count: 38 

享受!

+0

非常感謝 !然後,如果我得到了相當數量的這種情況下編號,我想要顯示如下:案例編號:0 案件內容:000000100 案件編號:1 案件內容:000000101 行數:38等.. 。 怎麼做 ? – YDev 2014-10-19 22:46:55

+0

@Yolk沒問題!請確保接受我的答案,如果它適合你。你的下一個問題有點複雜,所以試着讓它工作,一旦你得到它,在Stack Overflow上發佈另一個問題,我會做出一個單獨的答案。 – 2014-10-19 22:50:33

+0

我只能發佈每90分鐘一次,我已經接受你的答案=)好吧,我得到的輸出是這樣的: 案件編號:-1 案例內容:000000100 行數:4085 我認爲有一點點案件號碼錯誤。 後來我有215套的情況下(在同一文件和相同的格式與第一組數據),我需要做的輸出,如: 案件編號:0 案例內容:000000100 案件編號:1 病例內容:000000101 病例號碼:2 病例內容:000010101 。 。 。(顯示所有的情況) 行數:4085 – YDev 2014-10-19 23:03:27

3

您可以通過線READFILE行:

BufferedReader reader = new BufferedReader(new FileReader("test.txt")); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     System.out.println(line); 

後,你可以檢查行字符串,如果它是數字與布爾函數

public static boolean isNumeric(String str) 
{ 
    try 
    { 
    double d = Double.parseDouble(str); 
    } 
    catch(NumberFormatException nfe) 
    { 
    return false; 
    } 
    return true; 
} 

OR喲你可以讀文件併爲行保留一個計數器,或者你可以有一個每次都改變的標誌,或者你可以使用str.contains(「:」);當你閱讀文件並以這種方式理解沒有你想要的內容時。

這是一個更多鈔票的解決方案:

package test; 

import java.io.FileNotFoundException; 
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
/** 
* 
* @author Alex 
*/ 
public class encrypt { 



public static boolean isNumeric(String str) 
{ 
    str.contains(str); 
    try 
    { 
    double d = Double.parseDouble(str); 
    } 
    catch(NumberFormatException nfe) 
    { 
    return false; 
    } 
    return true; 
} 
    public static void main(String[] args) throws FileNotFoundException, IOException { 
     // TODO code application logic here 

     String mycase="caseNumber :", case_cont="case content :"; 


     BufferedReader reader = new BufferedReader(new FileReader("test.txt")); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      //System.out.println(line); 
      if(line.contains("case")) 
      { 
       mycase=mycase+line.replace("case", "").replace(":", ""); 
      } 
      else if(isNumeric(line)==true) 
      { 
       case_cont=case_cont+line.replaceAll("\\s+",""); 
      } 
     } 
     System.out.println(mycase); 
     System.out.println(case_cont); 
    } 
} 
+0

一個偉大的方法做它,以及什麼情況!謝謝 ! OMG! – YDev 2014-10-19 22:49:30

2

試試這個代碼

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 
import java.util.StringTokenizer; 

public class FileScanner { 

    File f = new File("test.txt"); 

    public static void main(String[] args) { 
     FileScanner fs = new FileScanner(); 

     fs.readfile(); 

    } 

    public void readfile() { 

     try { 

      Scanner scanner = new Scanner(f); 
      StringBuilder builder = new StringBuilder(); 
      List<String>strings = new ArrayList<String>(); 
      StringTokenizer st ; 
      int lineCount = 0; 
      while (scanner.hasNextLine()) { 
       lineCount++; 
       String line = scanner.nextLine(); 
       line = line.trim(); 
       builder.append(line +" "); //better then String s+= line 
      } 
      scanner.close(); 
      st = new StringTokenizer(builder.toString()," "); 
      builder = new StringBuilder(); 
      while(st.hasMoreElements()){ 
       String s = st.nextElement().toString(); 
       if(s.contains("a")&&s.contains(":")&&!s.contains("case")){ 
        continue; 
       } 
       else if(s.contains("case")){ 
        builder.append(":"+s); 
       } 
       else{ 
        builder.append(s); 
       } 
      } 
      st = new StringTokenizer(builder.toString(),":"); 
      while(st.hasMoreElements()){ 
       strings.add(st.nextElement().toString()); 

      } 
      for(int i=0;i<strings.size()-1;i++){ 
       if(strings.get(i).contains("case")){ 
        System.out.println("Case Number: " + strings.get(i)); 
        if(i+1 <strings.size()){ 
         System.out.println("Case Contents: " + strings.get(i+1)); 
        } 

       } 
      } 
      System.out.println("line count : " + lineCount); 

     } catch (FileNotFoundException e) { 

     } 

    } 
} 
+0

這很酷!但是如果我需要單獨的數組,如何處理它呢?我需要一個只包含casenumbers的CaseNumStrings數組和一個只包含casecontents的CaseContStrings數組。然後我可以做一些像System.out.println(「第40個案例編號是:」+ CaseNumStrings [40]); System.out.println(「第40個案例內容是:」+ CaseNumStrings [40]); – YDev 2014-10-20 17:21:38

2

我做了一些修改,讓你選擇你想打印

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 
import java.util.StringTokenizer; 

public class FileScanner { 

    File f = new File("test.txt"); 
    List<String>cases = new ArrayList<String>(); 
    List<String>contents = new ArrayList<String>(); 
    List<String>strings = new ArrayList<String>(); 
    public static void main(String[] args) { 
     FileScanner fs = new FileScanner(); 

     fs.readfile(); 
     for(int i = 0; i<fs.getCases().size();i++){ 
      System.out.println("case number is : "+ fs.getCase(i)); 
      System.out.println("case content is : "+fs.getContent(i)); 

     } 
    } 

    public void readfile() { 

     try { 

      Scanner scanner = new Scanner(f); 
      StringBuilder builder = new StringBuilder(); 

      StringTokenizer st ; 
      int lineCount = 0; 
      while (scanner.hasNextLine()) { 
       lineCount++; 
       String line = scanner.nextLine(); 
       line = line.trim(); 
       builder.append(line +" "); //better then String s+= line 
      } 
      scanner.close(); 
      st = new StringTokenizer(builder.toString()," "); 
      builder = new StringBuilder(); 
      while(st.hasMoreElements()){ 
       String s = st.nextElement().toString(); 
       if(s.contains("a")&&s.contains(":")&&!s.contains("case")){ 
        continue; 
       } 
       else if(s.contains("case")){ 
        builder.append(":"+s); 
       } 
       else{ 
        builder.append(s); 
       } 
      } 
      st = new StringTokenizer(builder.toString(),":"); 
      while(st.hasMoreElements()){ 
       strings.add(st.nextElement().toString()); 

      } 

      for(int i=0;i<strings.size();i++){ 
       if(strings.get(i).contains("case")){ 
        cases.add(strings.get(i)); 
       } 
       else{ 
        contents.add(strings.get(i)); 
       } 
      } 
      System.out.println("line count : " + lineCount); 

     } catch (FileNotFoundException e) { 

     } 

    } 


    public String getCase(int index) { 
     if(!cases.isEmpty() &&index <cases.size()){ 
      return cases.get(index); 
     } 
     return "NaN"; 
    } 


    public String getContent(int index) { 
     if(!contents.isEmpty() &&index <contents.size()){ 
      return contents.get(index); 
     } 
     return "NaN"; 
    } 


    public List<String> getCases() { 
     return cases; 
    } 


    public void setCases(List<String> cases) { 
     this.cases = cases; 
    } 


    public List<String> getContents() { 
     return contents; 
    } 


    public void setContents(List<String> contents) { 
     this.contents = contents; 
    } 

} 
+0

太棒了!完美的工作!非常感謝 ! – YDev 2014-10-20 19:29:14