我正在研究这个非常简单的方法,我知道我已经很接近完成它了,但是我缺少一个细节。感谢您的帮助。谢谢。

/**
  Gets the first letter in this string.
  @return the FIRST LETTER, or "" if there are no letters.
  add1=AD3F add2=EF4G result=32SFB  (BUT THESE ARE RANDOM ONLY INTS AND CHARS)
*/
public String firstLetter()
{
    String line = add1+add2+result;

    for(int i=0; i<line.length(); i++){
    char ch=new Character(line.charAt(i));
    if(Character.isLetter(ch)){
        System.out.println("This is the first letter"+ch);
        return ch;
    }
    else
        System.out.println("No it is not a character: "+ch);
    return "";
    }

最佳答案

您需要将else代码移到循环外,以便仅在测试所有字符后才执行:

public class FirstLetter
{
    public static void main(String[] args)
    {
        System.out.println(firstLetter());
    }

    public static String firstLetter()
    {
        String line = "AD3F" + "EF4G" + "32SFB";

        for (int i = 0; i < line.length(); i++)
        {
            char ch = line.charAt(i);
            if (Character.isLetter(ch))
            {
                System.out.println("This is the first letter: " + ch);
                return Character.toString(ch);
            }

        }
        System.out.println("No character found");
        return "";
    }
}


当您清楚地格式化代码时,这种问题更加明显。

我将返回类型保留为原始的String,但也请参阅乔恩·斯凯特(Jon Skeet)关于将其更改为char的评论。

关于java - 从字符串中获取字母的第一个实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9447947/

10-11 01:29
查看更多