2017-12-01 8 views
1

検索エンジンを作成して、ユーザーが指定した単語と一致する文書を見つけようとしています。以下は私のコードです。これは私の方法です。ユーザーの入力を覚えていますが、検索に少し追加するつもりですが、これを多く試してみました(これが入力をプリントアウトしている理由です)。入力を受け入れる。私は何を変更して、ユーザーが行を空白にしておくまで多くの単語を取りますか?私は10時に停止するようにしたが、空白のままにしておくとhasNext()はそれを止めるだろうと思ったが、ただスキャンを続ける。スキャナからの入力量が不定

Scanner userInput = new Scanner(System.in); 
    System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):"); 
    String[] stringArray = new String[10]; 
    int i = 0; 

    while (userInput.hasNext() && i < 9){//takes input until user leaves a blank line 
     stringArray[i] = userInput.next(); 
     i++; 
    } 
    for (int j = 0; j < i; j++){//just for testing purposes 
     System.out.println(stringArray[j]); 
    } 

答えて

1
String line; 
int i = 0; 
while(!(line = userInput.nextLine()).isEmpty()) { 
    for (String word :line.split("\\s+")){ 
     stringArray[i]=word; 
     i++; 
    } 
} 

ユーザー入力空でなくなるまで、このコードは変数lineScannerからすべての行を割り当てます。すべての反復では、lineを単語に分割し、stringArrayに割り当てます。

+0

これはうまくいった!ありがとう! –

0
はこれにあなたのwhileループを変更

while (!(String temp = userInput.nextLine()).trim().contentEquals("")) { 
    stringArray[i] = userInput.next(); 
    i++; 
} 
+2

このコードはコンパイルされません。 'Scanner#hasNext()'のboolean結果を 'String'変数に代入しようとしています。 – Bedla

+0

ああ、はい、そうです。 .nextLine()が必要です。私の謝罪は、今編集する。 – Neytorokx

0

hasNext() & next()言葉ではなく行で停止します。あなたのコードでは、ユーザーは同じ行に10単語すべてを置くことができ、それらは完了します。また、これらのメソッドは、改行文字を含むすべての空白を、次の単語が見つかるまでスキップします。 hasNext()next()を使用して空白行を検索することはできません。空の文字列を返すことはできません。代わりにhasNextLine()nextLine()が必要です。

Scanner userInput = new Scanner(System.in); 
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):"); 
String[] stringArray = new String[10]; 
int i = 0; 

while (i < stringArray.length 
     && userInput.hasNextLine() 
     && !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) { 
    i++; 
} 

for (int j = 0; j < i; j++) { // just for testing purposes 
    System.out.println(stringArray[j]); 
} 

なぜ10行に制限するのですか?代わりにArrayListを使用して柔軟性を高めることができます。

Scanner userInput = new Scanner(System.in); 
System.out.println("\n\n\nEnter the words you would like to search your documents for:"); 
List<String> stringList = new ArrayList<>(); 
String line; 

while (userInput.hasNextLine() 
     && !(line = userInput.nextLine().trim()).isEmpty()) { 
    stringList.add(line); 
} 

stringList.forEach(System.out::println); // just for testing purposes 
関連する問題