N
N
Newbie Ivanovich2021-03-22 06:20:51
Java
Newbie Ivanovich, 2021-03-22 06:20:51

Why does it incorrectly count how many times a letter was used when reading from a string to an array?

The code

Scanner sc;
        String[] strArray = {"t", "e", "s", "t", "t","s", "t"}; //Если задать значение сразу то считает правильно
        //    String[] strArray;
        Map<String, Integer> map = new HashMap<String, Integer>();
        int i, j;

//        System.out.println("Введите слово и нажмите Enter");
//        sc = new Scanner(System.in);
//        strArray = sc.nextLine().split("");    Если считать из строки в массив то считает не правильно
        int d = strArray.length;

        for (i = 0; i < d; i++) {
            String b = strArray[i];
            int count = 0;
            for(j = 0; j < d; j++) {
                if (b == strArray[j]) {
                    count++;
                    map.put(b, count);
                }
            }
        }
        System.out.println(map);



If the array is initialized immediately, without receiving the array through the Scaner.nextline.split("") method, then it is considered correct, otherwise it is incorrect, although there is also a string array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-03-22
@NovichokIvanovich

Two reasons:
1. Because strings in Java are compared using the .equals method 2.
Because Java's string pool
", "t" is the same object (so are "s", "s"), and so "t" == "t" // true
In case you take a string and split its split - it turns out an array of already different objects, albeit with the same content, which can be correctly compared using the .equals
String pool method in java - the topic of a separate article, do not be too lazy to read (besides, they love it at interviews).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question