简体   繁体   English

子串不等于第一个字符的串

[英]Substring not equal to the string of the first character

I am struggling to figure out what's wrong with my code.我正在努力弄清楚我的代码有什么问题。 When the user input is "apple" I get that it doesn't begin with a vowel.当用户输入是“apple”时,我知道它不是以元音开头。

import java.util.*;
public class StringeExerciseElearn {
    public static void main(String[] args) {
        Scanner k = new Scanner(System.in);
        System.out.println("Type a word: ");
        String input = k.next();
        String l = input.substring(0);
        String a = "a";
        String e = "e";
        String i = "i";
        String o = "o";
        String u = "u";

        if(l.equals(a) || l.equals(e) || l.equals(i) || l.equals(o) || l.equals(u))
            System.out.println(input + " begins with a vowel!");
        else
            System.out.println(input + " doesn't begin with a vowel");
        }
    }
}

Use startWith method of String , it will work fine.使用 String 的 startWith 方法,它会正常工作。

public class Practice {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner k = new Scanner(System.in);
    System.out.println("Type a word: ");
    String input = k.next();
    String l = input;
    String a = "a";
    String e = "e";
    String i = "i";
    String o = "o";
    String u = "u";

    if (l.startsWith(a) || l.startsWith(e) || l.startsWith(i) || l.startsWith(o) || l.startsWith(u))
        System.out.println(input + " begins with a vowel!");
    else
        System.out.println(input + " doesn't begin with a vowel");
}

input.substring(0) returns the String starting at the index 0 and extending the length of the string. input.substring(0)返回从索引 0 开始并扩展字符串长度的字符串。 In other words, it returns the input string;换句话说,它返回输入字符串; eg "apple".substring(0) returns "apple".例如"apple".substring(0)返回“apple”。

To get a single characters substring, you need to use the version of the substring method that takes both a begin index and an end index — public String substring​(int beginIndex, int endIndex) :要获取单个字符的子字符串,您需要使用同时接受开始索引和结束索引的 substring 方法版本 — public String substring​(int beginIndex, int endIndex)

String l = input.substring(0, 1);

Note that this will throw an IndexOutOfBoundsException for the empty string ( "" ).请注意,这将为空字符串 ( "" ) 抛出IndexOutOfBoundsException To prevent this, the string's length should also be checked before doing the substring check.为了防止这种情况,在进行substring检查之前还应该检查字符串的长度。

You made a mistake using the substring method, you should say the start position in first parameter and the length desires of the substring in second parameter :您使用 substring 方法犯了一个错误,您应该在第一个参数中说明开始位置,在第二个参数中说明子字符串的长度要求:

String l = input.substring(0, 1);

And now it works fine :) :现在它工作正常:):

Type a word: 
apple
apple begins with a vowel!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM