绝对java教科书示例错误

时间:2016-09-08 23:38:43

标签: java string

无法弄清楚我所犯的小错误。这个例子来自Absolute java教科书。

public class Display1_7 {

    public static void main(String[] args) {

        String sentence = "I hate text processing!";
        int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
        String ending = sentence.substring(position = "hate".length());/*cuts out the first half
                                                                        of the sentence*/

        System.out.println("0123456789");
        System.out.println(sentence);
        System.out.println("The word \"hate\" starts at index " 
                            + position);/*example of using quotes inside a string,
                                        also demonstrates concatenation of a variable*/

        sentence = sentence.substring(0, position) + "adore"+ ending;//I think I did this wrong?

        System.out.println("The changed string is:");
        System.out.println(sentence);
    }//end of main
 }

预期输出

here

我得到的输出是here

2 个答案:

答案 0 :(得分:2)

当您尝试确定=时,您使用的是+而不是ending

String ending = sentence.substring(position + "hate".length());

......应该做的伎俩

答案 1 :(得分:1)

问题是您的String ending = sentence.substring(position ="hate".length());应为String ending = sentence.substring(position +"hate".length()); 实际上,结尾是仇恨的位置(由IndexOf()返回),您可以在其中添加要删除的单词的长度(在本例中为“hate”)。 您在代码中的赋值实际上改变了从2切换到4(仇恨的长度)的位置值。因此,不仅结尾字符串错了,而且你的位置也是错误的,最终String正是你所拥有的。

所以这是您的代码的更正(和工作)版本

public class Display1_7 {

    public static void main(String[] args) {

        String sentence = "I hate text processing!";
        int position = sentence.indexOf("hate");//finding the position of hate in variable sentence
        String ending = sentence.substring(position +"hate".length());/*cuts out the first half
                                                                        of the sentence*/

        System.out.println("0123456789");
        System.out.println(sentence);
        System.out.println("The word \"hate\" starts at index " 
                            + position);/*example of using quotes inside a string,
                                        also demonstrates concatenation of a variable*/

        sentence = sentence.substring(0, position) + "adore"+ ending;

        System.out.println("The changed string is:");
        System.out.println(sentence);
    }
 }

小记,我会避免像“主要结束”这样的评论,我的意思是根本没有任何意义,任何人都可以理解这是主要的结束:)。从我收集到的你是一个初学者,但是,这种评论只会让有用的评论逐渐消失。