簡體   English   中英

如何從Java中的文本文件中提取數據

[英]how to extract data from text file in Java

while (myFile.hasNextLine()) {

if(myFile.next().equals("Oval")) { System.out.println("this is an Oval"); } else if(myFile.next().equals("Rectangle")) { System.out.println("this is an Rectangle"); }

該文件包含以下內容
橢圓10 10 80 90紅色
橢圓20 20 50 60藍色
矩形10 10100100綠色

我想提取數據並將其根據行開頭指示的類型傳遞給特定的構造函數。

但我得到這個奇怪的輸出

這是線程“ main”中的卵形異常java.util.NoSuchElementException這是java.util.Scanner.throwFor(Scanner.java:907)處的矩形。這是java.util.Scanner.next(Scanner.java)中的矩形。 :1416)位於sun.reflect.NativeMethodAccessorImpl.invoke的TestMain.main(TestMain.java:33)invoke0(位於sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethod)的本地方法)(NativeMethodAccessorImpl.java:57)位於sun.reflect.DelegatingMethodAccessorImpl.invoke(在com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)處java.lang.reflect.Method.invoke(Method.java:601)處的DelegatingMethodAccessorImpl.java:43)

流程以退出代碼1完成

請理解,當您在Scanner對象上調用next()時,它將吞噬下一個令牌,然后將其返回給您。 如果不將返回的String分配給變量,它將永遠丟失,並且下次調用next()您將獲得一個新令牌。 獲得令牌更好,將其分配給String變量,然后進行if測試。 不要在if布爾測試塊中調用next()

即,類似:

while (myFile.hasNextLine()) {

    // get the token **once** and assign it to a local variable
    String text = myFile.nextLine();

    // now use the local variable to your heart's content    
    if(text.equals("Oval")) {
        System.out.println("this is an Oval");

    }

    else if(text.equals("Rectangle")) {
        System.out.println("this is an Rectangle");

    } 

另外,如果您測試hasNextLine() ,則應調用nextLine() ,而不要調用next() ,並且對於每個hasNextLine只能調用一次


從文本文件提取數據行時,有時會使用多個Scanner。 例如:

Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
  Scanner lineScanner = new Scanner(fileScanner.nextLine());

  // use the lineScanner to extract tokens from the line

  lineScanner.close();
}
fileScanner.close(); // likely done in a finally block after null check

您需要將next()hasNext()方法調用進行匹配,以匹配單個String令牌

while (myFile.hasNext()) {
   String token = myFile.next();

    if (token.equals("Oval")) {
       System.out.println("this is an Oval");
    }
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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