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
时,您的代码正在等待用户输入两行。
要解决此问题,您需要:
- 使用
nextLine
读取整行。 - 使用
sentence
而不是第二次请求用户输入。
这样的事情应该有效:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
关于java - 尝试从用户输入中获取句子的长度,但在第一个单词和空格后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106220/