2017-10-10 18 views
2

私は大学の入門Javaコースです。私の任務のためには、文章中の1文字の単語数、文章中の2文字の単語数などを表示するプログラムを書く必要があります。その文章はユーザが入力したものです。私はループを使用することになっており、配列を使用することはできません。文章の最初の単語の文字数を数えてください。

しかし、今のところ始めてみると、私は文章の最初の単語の文字数を見つけようとしています。私が持っているものは、誤った文字数か、Stringインデックスが範囲外であるというエラーです。

Scanner myScanner = new Scanner(System.in); 

    int letters = 1; 

    int wordCount1 = 1; 

    System.out.print("Enter a sentence: "); 
    String userInput = myScanner.nextLine(); 


    int space = userInput.indexOf(" "); // integer for a space character 

    while (letters <= userInput.length()) { 

    String firstWord = userInput.substring(0, space); 
    if (firstWord.length() == 1) 
     wordCount1 = 1; 
    int nextSpace = space; 
    userInput = userInput.substring(space); 
    } 
    System.out.print(wordCount1); 

I入力は、それが「範囲外の文字列インデックス:4」私を与える「これは文である」例えばこれで任意の助けをいただければ幸いです。

+0

ここでは、デバッガの使い方を学ぶのに適しています。変数 "space"の値は何ですか? – OldProgrammer

+0

'space'の値は決して更新されません –

答えて

0

で試してみてください:

int len = userInput.split(" ")[0].length(); 

そして、これは単に配列の最初の位置を取得し、最終的には長さを取得し、あなたに空白で分割さ単語の配列を与えます。

+0

あなたの答えはありがとうございます。残念ながら私はクラスでまだそれらをカバーしていないので、私は配列を使用することはできません。 –

0
userInput.indexOf(" "); 

これは、配列を使用しない最初の単語の長さを示します。 spaceが更新されることはありませんから、コードは2の長さの文字列から4へサブインデックス0にしようとしてしまい、ため

はStringIndexOutOfBoundsExceptionをがスローされます。

userInputがwhileループで印刷した場合、出力は次のようになります。そしてStringIndexOutOfBoundsがスローさ

This is a sentence 
is a sentence 
a sentence 
ntence 
ce 

私は、配列を使用せずに文からすべての単語を数えるような方法は、次のようになります。

Scanner in = new Scanner(System.in); 

System.out.print("Enter a sentence: "); 
String input = in.nextLine(); 
in.close(); 

int wordCount = 0; 

while (input.length() > 0) { 
    wordCount++; 
    int space = input.indexOf(" "); 
    if (space == -1) { //Tests if there is no space left 
     break; 
    } 
    input = input.substring(space + 1, input.length()); 
} 

System.out.println("The number of word entered is: " + wordCount); 
+0

ありがとうございました。私は今問題を理解している、私はちょうどそれを修正する方法を知らない。私は問題が 'userInput = userInput.substring(space); 'であると思います。これは次の単語と文の残りの部分に移動するはずですが、間違っています。 –

+0

編集済みanwserを見る... –

0

あなたの問題は、あなたがスペースや文字を更新していないということでした。 下のコードを参考にしてうまくいくはずです。

Scanner myScanner = new Scanner(System.in); 

     int letters = 1; 

     int wordCount1 = 1; 
     String firstWord = null; 

     System.out.print("Enter a sentence: "); 
     String userInput = myScanner.nextLine(); 


     int space = -2; //= userInput.indexOf(" "); // integer for a space character 

     while (letters <= userInput.length() && space != -1) { 

     space = userInput.indexOf(" "); 
     if (space != -1) 
      firstWord = userInput.substring(0, space); 
     if (firstWord.length() == 1) 
      wordCount1 = 1; 
     userInput = userInput.substring(space + 1); 
     } 
     System.out.print(wordCount1); 
} 
関連する問題