使用数组

时间:2015-11-25 01:36:40

标签: java arrays

我一直在研究这个问题已经两天了,不知道我哪里出错了。

基本上我需要向用户询问一串单词。 我需要设置一个包含26个元素的int数组,其中包含小写字母数和一个大写字母数。

我无法让程序正确地与数组元素进行比较。到目前为止,这是我的代码:

public class Lab17Array {

    public static void main(String[] args) 
    {
        Scanner kb = new Scanner (System.in);
        int lLetter = 0;
        int uLetter = 0;

        // int[] alph = new int [26];
        int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

        System.out.println("Enter a phrase");
        String user = kb.nextLine();
        // to print out length of word
        System.out.println("Total number of letters is " + user.length());

        for(int i = 0; i < user.length(); i++)
        {


        }

        System.out.println("Upper case letters are:" + uLetter);
        System.out.println("Lower case letters are:" + lLetter);
        int otherL = user.length() - (uLetter + lLetter);

        // to print out other chars that aren't letters
        System.out.println("Number of all other letters is " + otherL );
    }
} 

在我的for循环中,如果条件不同,我一直在尝试不同的地方。我不知道我错过了什么?

3 个答案:

答案 0 :(得分:1)

使用数组

您可以使用String.toCharArray()for-each loop来迭代user输入(您似乎更改了帖子和评论之间的变量名称)。无论如何,像

for (char ch : user.toCharArray()) {
    if (Character.isLowerCase(ch)) {
        lLetter++;
    } else if (Character.isUpperCase(ch)) {
        uLetter++;
    }
}

使用正则表达式

您可以使用正则表达式从输入中删除所有非小写字符以及从输入中删除所有非大写字符(如

)来减少代码
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z

答案 1 :(得分:0)

试试这个

usePoll

答案 2 :(得分:0)

试试这个。

    for(int i = 0; i < user.length(); i++)
    {
        int ch = user.charAt(i);
        if (Arrays.binarySearch(alph, ch) >= 0)
            ++lLetter;
        if (Arrays.binarySearch(Alph, ch) >= 0)
            ++uLetter;
    }