我正在尝试输入一个四字的句子,然后能够使用indexOf和substrings分别打印出每个单词。我有什么想法我做错了吗?
被修改
它应该是什么样子?我已经运行了两次并收到两个不同的答案,所以我不确定运行该程序的程序是否有问题或程序本身是否有问题。
import java.util.Scanner;
public class arithmetic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String sentence;
String word1, word2, word3, word4;
int w1, w2, w3, w4;
int p, p2, p3, p4;
System.out.print("Enter a sentence with 4 words: ");
sentence = in.nextLine();
p = sentence.indexOf(" ");
word1 = sentence.substring(0,p)+" ";
w1 = 1 + word1.length();
p2 = word1.indexOf(" ");
word2 = sentence.substring(w1,p2);
w2 = w1+1+word2.length();
p3 = word2.indexOf(" ");
word3 = sentence.substring(w2,p3);
w3 = w1+w2+1+word3.length();
p4 = word3.indexOf(" ");
word4 = sentence.substring(w3,p4);
w4 = w1+w2+w3+1+word4.length();
答案 0 :(得分:1)
我至少看到两件事:
length of first word + 1 + length of second word + 1
,但看起来你要忽略第一个单词的长度。同样地,当你得到第四个单词时,你会忽略前两个单词的长度。indexOf(" ")
只会获取第一次出现空格的索引。获得第一个空格后,您将重用该索引,而不是使用其他空格的索引。最后,在你修复这两个之后,如果你知道这些单词将被空格分隔,那么你可能想要查看String.split
函数。使用它,您可以分割您的句子而无需自己进行所有空间查找。
答案 1 :(得分:1)
由于性能原因,可读性和错误,我几乎不建议不使用substring
和indexOf
。考虑以下任何一个(所有这些都将单词视为非空白字符):
public static void main (String[] args) throws java.lang.Exception
{
int wordNo = 0;
System.out.println("using a Scanner (exactly 4 words):");
InputStream in0 = new ByteArrayInputStream("a four word sentence".getBytes("UTF-8"));
Scanner scanner = new Scanner(/*System.*/in0);
try {
String word1 = scanner.next();
String word2 = scanner.next();
String word3 = scanner.next();
String word4 = scanner.next();
System.out.printf("1: %s, 2: %s, 3: %s, 4: %s\n", word1, word2, word3, word4);
} catch(NoSuchElementException ex) {
System.err.println("The sentence is shorter than 4 words");
}
System.out.println("\nusing a Scanner (general):");
InputStream in1 = new ByteArrayInputStream("this is a sentence".getBytes("UTF-8"));
for(Scanner scanner1 = new Scanner(/*System.*/in1); scanner1.hasNext(); ) {
String word = scanner1.next();
System.out.printf("%d: %s\n", ++wordNo, word);
}
System.out.println("\nUsing BufferedReader and split:");
InputStream in2 = new ByteArrayInputStream("this is another sentence".getBytes("UTF-8"));
BufferedReader reader = new BufferedReader(new InputStreamReader(/*System.*/in2));
String line = null;
while((line = reader.readLine()) != null) {
for(String word : line.split("\\s+")) {
System.out.printf("%d: %s\n", ++wordNo, word);
}
}
}