试图从用户输入中获取句子的长度,但它在第一个单词和 space 之后停止

Trying to get the length of a sentence from a user input but it stops after the first word and space

Java任务是让用户输入一个sentence/phrase然后打印出这个句子有多少个字符。我的 .length() 方法只计算第一个单词和 space 作为字符。我已经阅读过以前涉及 nextLine() 的问题和答案,但如果我使用它而不是 next(),它只会让用户键入它的问题并等待,不会立即打印任何其他内容。我是 Java 的新手,我认为这可以用定界符修复,但我不确定我是如何或遗漏了什么。 TIA!!

更新: 这是我的代码。

import java.util.Scanner;

class StringStuff{
   public static void main( String [] args){

      Scanner keyboard = new Scanner(System.in);
      int number;

      System.out.print("Welcome! Please enter a phrase or sentence: ");
      System.out.println();
      String sentence = keyboard.next();
      System.out.println();

      int sentenceLength = keyboard.next().length();


      System.out.println("Your sentence has " + sentenceLength + " characters.");
      System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
      System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");


   }
}

当我输入 "Hello world." 作为它打印的句子时:

你的句子有6个字。 你的句子的第一个字符是 H。 第一个space的索引是-1。

keyboard.next 调用正在等待用户输入。您调用了两次,因此您的程序希望用户输入两个单词。

因此,当您输入 "Hello world." 时,它会分别读取 "Hello" 和 "world.":

//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();

//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();

当您使用 nextLine 时,您的代码正在等待用户输入两行。

要解决此问题,您需要:

  1. 阅读整行nextLine
  2. 第二次使用sentence而不是请求用户输入。

像这样的东西应该可以工作:

String sentence = keyboard.nextLine();
System.out.println();

int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
 public static void main(String args[])
 {
 Scanner s=new Scanner(System.in);
 System.out.println("enter the sentence:");
 String str=s.nextLine();
 int count = 0;
 System.out.println("The entered string is: "+str);    
 for(int i = 0; i < str.length(); i++) 
    {    
        if(str.charAt(i) != ' ')    
            count++;    
    }
    System.out.println("Total number of characters in the string: " + count);  
    System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
  System.out.println("The index of the first space is " + str.indexOf(" ") + ".");  
}      

}