Answer the question
In order to leave comments, you need to log in
Why does it incorrectly count how many times a letter was used when reading from a string to an array?
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);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question