字符串不等于

问题描述 投票:-1回答:2

我正在努力找出我的代码出了什么问题。当用户输入为“ apple”时,我得到它不是以元音开头的。请帮助。

import java.util.*;
public class StringeExerciseElearn {

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.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");
    }
}
java string equality
2个回答
0
投票

您在使用substring方法时犯了一个错误,您应该在第一个参数中说出开始位置,并在第二个参数中说出子串的长度期望:

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

现在工作正常:):

Type a word: 
apple
apple begins with a vowel!

0
投票

使用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");
}
© www.soinside.com 2019 - 2024. All rights reserved.