簡體   English   中英

如何不清除Java中的掃描程序緩沖區?

[英]How to Not clean Scanner buffer in Java?

我有這樣的事情:

InputStream in = new InputStream(fileName);
Scanner sc = new Scanner(in);
String nextWord;
String anotherWord;

while(sc.hasNext()) {
  nextWord = sc.next();
  ...
  ...
}

while(sc.hasNext()) {
anotherWord = sc.next();
...
...
}

第二個循環將不起作用,因為sc.next()讀取令牌后,掃描程序的緩沖區將被清除。 如何在不清除掃描儀緩沖區的情況下讀取令牌,因此可以在第二個循環中使用sc

您可以像這樣重新初始化掃描儀。

InputStream in = new InputStream(fileName);
Scanner sc = new Scanner(in);
String nextWord;
String anotherWord;

while(sc.hasNext()) {
  nextWord = sc.next();
  ...
  ...
}
sc = new Scanner(in);
while(sc.hasNext()) {
    anotherWord = sc.next();
    ...
    ...
}
 nextWord = sc.next();
 nextToNextWord = sc.next();
 nextToNextToNext = sc.next();

 anotherWord = sc.next();
 anotherOneWord= sc.next()
 anotherTwoWord = sc.next()

您無需循環即可在此處讀取,除非放入數組或Collection

暫無
暫無

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

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