Java的任务是让用户键入一个句子/短语,然后打印出该句子有多少个字符。我的.length()方法仅将第一个单词和空格作为字符进行计数。我已经阅读了涉及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。
第一个空格的索引是-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时,您的代码正在等待用户输入两行。

要解决此问题,您需要:


nextLine读取整行。
使用sentence而不是第二次请求用户输入。


这样的事情应该起作用:

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

int sentenceLength = sentence.length();

关于java - 试图从用户输入中获取句子的长度,但是在第一个单词和空格之后停止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60106220/

10-11 19:59