簡體   English   中英

計算句子的第一個單詞中的字母數

[英]Count the number of letters in the first word of a sentence

我在大學里參加入門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);

例如,當我輸入“這是一個句子”時,它給我“字符串索引超出范圍:4”。對此的任何幫助將不勝感激。

嘗試:

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

這將為您提供由空格分隔的單詞數組,然后僅獲得數組中的第一個位置,最后獲得長度。

userInput.indexOf(" ");

這使您可以不使用數組而獲得第一個單詞的長度。

拋出StringIndexOutOfBoundsException是因為,由於從不更新space ,因此代碼最終嘗試從長度為2的字符串將索引0子字符串化為4

如果將userInput打印在while循環中,則輸出為:

This is a sentence
 is a sentence
a sentence
ntence
ce

然后拋出StringIndexOutOfBounds。

我不使用數組就可以計算句子中每個單詞的方式是:

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);

您的問題是您尚未更新空格和字母。 看到下面的代碼,我的一些小改動應該可以正常工作。

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);
}

暫無
暫無

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

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