toLowerCase()方法似乎不起作用

时间:2015-01-10 20:57:21

标签: java

我一直在编写一个程序来计算字符串数组中字母的出现次数。为了做到这一点,我已经将每个输入小写,所以当搜索指定的字母时,它都以小写形式完成。当搜索的字母以小写字母输入时,程序工作,但在大写字母时不能工作。我对此感到困惑,因为我已经使用toLowerCase()方法使输入的字母小写,尽管输入了什么。任何帮助将不胜感激。

import java.util.Scanner;
public class RunStringArray
{

    public static void main (String [] args){

        int arrayLength;
        int count = 0;
        String word;
        String letter;
        int letterCount = 0;
        int x = 0;

        //Asks user for length of array
        Scanner kbInput = new Scanner(System.in);
        System.out.println("Enter a positive integer");
        arrayLength = kbInput.nextInt();

        //Makes sure array length is a valid number
        while (arrayLength <= 0){
            System.out.println("Invalid input (not positive)");
            System.out.println("Enter a positive integer");
            arrayLength = kbInput.nextInt();
        }
        //Creates array of the user specified length
        String words [] = new String [arrayLength];

        //Asks user to input all strings in the array and makes them lower case.
        kbInput.nextLine();
        while (count < words.length){
            System.out.println("Enter a string");
            word = kbInput.nextLine();
            word = word.toLowerCase();
            words[count] = word;
            count++;
        }

        //Asks user what letter he/she wants to count in the array
        System.out.println("What letter do you want to count?");
        letter = kbInput.nextLine();
        letter.toLowerCase();

        //Error trap making sure the user inputs a letter.
        while (letter.length() > 1){
            System.out.println("Invalid input (not a letter)");
            System.out.println("What latter do you want to count?");
            letter=kbInput.nextLine();
            letter.toLowerCase();
        }


        char c = letter.charAt(0);


        //While loop which will count the occurrence of the letter in each 
        //string in the array, and then adds all of the occurrences together
        //in order to find the total occurrences of the letter.  
        while (count > 0){  
            letterCount = RunStringArray.count(words[count-1], c);
            x += letterCount;       
            count--;
        }

        System.out.println(x);
    } //End of main

    private static int count (String str, char searchLetter){
        int occurrences = 0;

        for (int k = 0; k < str.length(); k++){
            if (str.charAt(k) == searchLetter)
            {
                occurrences++;
            } //End of if
        } //End of for loop
        return occurrences;

    } //End of method

} //End of class

2 个答案:

答案 0 :(得分:4)

您没有存储letter.toLowerCase()的输出。

更改

letter.toLowerCase();

letter = letter.toLowerCase();

答案 1 :(得分:1)

在Strings,Integers,Long等上执行的方法将生成新对象。这就是为什么你需要分配这些值。原因:字符串和所有这些类型都是不可变的,当你创建新的对象时,你无法改变它的值。

letter = kbInput.nextLine().toLowerCase();