簡體   English   中英

使用掃描儀時邏輯錯誤。 文本文件的第一行未打印到標准輸出

[英]Wrong logic in using scanner. The first line of the text file is not printed out to stdout

我有以下代碼和一個具有所有數字的輸入文件,因此txt文件中的每一行只有一個數字。 我將每行上的每個數字打印到標准輸出上,如果遇到數字42,則停止打印。但是問題是我用來讀取文件的掃描儀對象未顯示第一個數字,而僅從第二個開始打印我的txt文件編號。 我認為這與我不知道的scan.nextline函數有關,但我希望掃描器具有getcurrent或類似的東西來簡化事情。 無論如何,任何人都可以告訴我如何解決此問題並顯示第一行。

這是我的代碼:

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


public class driver {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub


        File theFile = new File("filepath.../input.txt");

        Scanner theScanner = new Scanner(theFile);

        //so that the scanner always starts from the first line of the document.
        theScanner.reset();


        while(theScanner.hasNext())
        {
            if(theScanner.nextInt() == 42)
            {
                break;
            }

            System.out.println(theScanner.nextInt());

        }
    }

}

問題是您在檢查時正在讀一個數字,然后再讀一個打印出的新數字。 這意味着您將每隔兩個數字打印一次。 要解決它,只需先存儲數字:

       int number = theScanner.nextInt() 
       if(number == 42)
        {
            break;
        }

        System.out.println(number);

在打印到標准輸出之前,我兩次在掃描程序對象上調用nextInt()方法。 一次在if語句中,再一次在System.out.println中。 因此,掃描儀從txt文件的第二行開始打印。

但是解決方案將包括如下代碼行:

 int temp = theScanner.nextInt();

在if語句之前,然后將if語句修改為:

if(temp == 42)
   { 
      break;

   }

   System.out.println(temp);

注意您調用了nextInt()方法有多少次。 即兩次,因此您的代碼必須跳過文件中的所有其他整數。 (如果僅從文件讀取兩個整數,則僅第一個數字)

因此,最簡單的解決方案是將整數存儲在局部變量中,然后使用它進行比較和打印。

即:

   while(theScanner.hasNext())
        {
            int nextInteger=theScanner.nextInt();
            if(nextInteger == 42)
            {
                break;
            }

            System.out.println(nextInteger);

        }
        theScanner.close();

暫無
暫無

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

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