[英]Java Scanner Class ( System.in)
當用戶使用 System.in 輸入文本時,我有以下代碼未讀取或無限循環。 如果我將文本硬編碼到 Scanner 變量中,它工作正常,所以我不確定此代碼的 System.in 部分有什么問題。 任何幫助表示贊賞。
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
因為System.in
在程序運行時始終可用,除非您關閉它。 它永遠不會退出 while 循環。 所以你可以添加else if (word.equals("exit")) { break; }
else if (word.equals("exit")) { break; }
. 這樣,無論何時鍵入“exit”,它都會關閉 while 循環並在 while 循環之后執行代碼。
如前所述,附加到 System.in 的掃描器會在尋找更多輸入時阻塞。 解決這個問題的一種方法是從掃描儀中讀取一行,對其進行標記,然后以這種方式循環遍歷單詞。 這看起來像這樣:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
您總是可以用一種循環結構(for、while、do-while)替換另一種。 他們都做同樣的事情,只是使用不同的語法,根據情況使一個比其他的更容易使用。 所以如果你想使用一個while循環,你可以這樣做:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
但是,我認為在循環一組已知數據的情況下,for 循環更清晰。 當數據集未知但退出條件已知時,while 循環會更好。
視情況而定,您是否只想閱讀 1 行文本,然后單獨計算單詞?
因為您只需要一行,所以您可以使用 Scanner 庫獲取輸入字符串並將字符串拆分為單個單詞,然后應用 if 語句。 就像是:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
這樣你就不需要 while 循環了。 所以它的處理器和內存效率更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.