Java中的indexOf +子字符串

时间:2018-12-10 14:54:25

标签: java

我被困在一项运动中,目标是输入一个名称并从名称中调出数值。例子(vanitoglo

然后,我必须使用方法substring()从字母中切出前3个字符并存储在可变新闻中-例如,我们有单词<van>

如果单词以<van>开头,我现在将这个变量<van>与单词<van>进行比较

我必须收到一条消息,即“输入的单词以<van>开头”

否则“单词不是以<van>开头”

我的问题是我不知道如何使用indexOf()搜索所有字符

例如,如果<van>在结尾或中间,我必须发出一条消息(“单词<van>到处都是”)

我已经在这里出现了错误消息:

word_search = name_enter.indexOf("van");

这是我的代码:

Scanner input = new Scanner(System.in);

String name_enter  = ""; //  enter the name
String word_sub    = ""; //  word slice
String word_search = ""; //  word search all over

System.out.print("Enter your name : ");

name_enter = input.next();
word_sub = name_enter.substring(0,3);
word_search = name_enter.indexOf("van");

if (word_sub.equals("van")) {
    System.out.print("The word begins with <van> ");
} else {
    if (word_search > 0) {
        System.out.print("the word <van> is included all over");
    } else {
        System.out.print("the word does not start with <van> ");
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用contains代替indexof,并且必须将“ word_search”参数设置为布尔值:

Scanner input = new Scanner(System.in);

String name_enter = "";   //  enter the name
String word_sub = "";     //  word slice
boolean word_search = false;  //  word search all over


System.out.print("Enter your name : ");
name_enter = input.next();

word_sub = name_enter.substring(0,3);

word_search = name_enter.contains("van");

if(word_sub.equals("van")){
    System.out.print("The word begins with <van> ");
}

else{
    if(word_search == true){
        System.out.print("the word <van> is included all over");

    }

    else{
        System.out.print("the word does not start with <van> ");
    }

}

答案 1 :(得分:0)

Scanner input = new Scanner();

String nameEntry = null;   //  enter the name
int vanIndex = 0;     //  index of van
boolean wordPresent = false;  //  word search all over

System.out.print("Enter your name :");
nameEntry = input.next();

vanIndex = nameEntry.indexOf("van");

if(vanIndex > 0){
    wordPresent = true;
}

if(wordPresent){
//do whatever
}