-2

During making programs about counting the number of alphabets each(e.g input-abc/output- a:1, b:1, c:1, d:0, ... , z:0)I have a problem. I don't know why the if clauses does not work... Here is my code.

import java.util.Scanner;


public class Prac05 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.nextLine();
        String[] b = a.split("");


        if (a.length() <= 100) {
            for (int i = 0; i < b.length; i++) {
                for (int j = 'a'; j <= 'z'; j++) {
                    if(b[i].equals((char) j)) {
                        System.out.println("1");
                    }
                }
            }
        }
    }

}

I am supposed to print "1", however since if-clauses does not true, nothing does output...

ANNE MAYOR
  • 47
  • 1
  • 6

1 Answers1

2

You are comparing a String object to a Character object, which do not equal each other because of their different types.

An easy solution, which will also result in more efficient and more elegant code is to use String.charAt(), rather than splitting the original string to a lot of small String objects, and iterate from 0 to a.length for each character in the string.

amit
  • 175,853
  • 27
  • 231
  • 333