1

我正在尝试输入一个四个单词的句子,然后能够使用 indexOf 和子字符串单独打印出每个单词。任何想法我做错了什么?

已编辑

这就是它应该的样子吗?我已经运行了两次,收到了两个不同的答案,所以我不确定我运行程序的程序有问题还是我的程序本身有问题。

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();
4

2 回答 2

1

我至少看到两件事:

  1. 您没有正确计算索引。第三个单词的起始索引应该类似于length of first word + 1 + length of second word + 1,但看起来您忽略了第一个单词的长度。同样,当你得到第四个单词时,你会忽略前两个单词的长度。
  2. indexOf(" ")只会为您提供第一次出现空格的索引。获得第一个空间后,您将重用该索引而不是使用其他空间的索引。

最后,在您修复这两个之后,如果您知道单词将由空格分隔,那么您可能需要查看该String.split函数。使用它,您可以拆分句子,而无需自己进行所有空间查找。

于 2013-09-12T21:16:57.507 回答
1

出于性能、可读性和错误的原因,我几乎不建议不要使用substringand 。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);
        }
    }
}
于 2013-09-12T21:36:20.377 回答