java - 尝试从用户输入中获取句子的长度,但在第一个单词和空格后停止

标签 java java.util.scanner delimiter string-length

Java 任务是让用户输入一个句子/短语,然后打印出该句子有多少个字符。我的 .length() 方法仅将第一个单词和空格计为字符。我已经阅读了之前涉及 nextLine() 的问题和答案,但如果我使用它而不是 next() ,它只会让用户输入它的问题并等待,不会立即打印任何其他内容。我是 Java 新手,我认为这可以通过分隔符来修复,但我不确定如何或缺少什么。蒂亚!!

更新:这是我的代码。

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时,您的代码正在等待用户输入两行。

要解决此问题,您需要:

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

这样的事情应该有效:

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

int sentenceLength = sentence.length();

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

相关文章:

php - 找出正则表达式的文件分隔符

matlab:分隔没有可用特定分隔符的 .csv 文件

java - 即使将 jsr94.jar 安装在结构正确的 m2 文件夹中,Maven 也无法检测到 jsr94.jar

java - 对象交互: Calculation on geometric shape

java.util.Scanner > useDelimiter() 结合 hasNextInt() before 和 nextInt() after

java - 使用 Scanner 填充对象的 ArrayList

java - Spring Boot 2.0 中的 RedisCacheManager.setCacheNames

java - cTAKES 和线程安全

java - BufferedReader 与 BufferedInputStream 的性能衡量

reactjs - 开 Jest 测试: custom currency/decimal formatters showed wrong delimiters