我已經編寫代碼來打印字符串中的第一個非重複字符,所有工作都正常。但是當打印字符時,它給出null。例如Sting input =「ttaasjji kkk eee」,那麼它應該打印's'作爲第一個非重複字符以下是我的java代碼。在使用java給出錯誤字符的字符串中第一個不重複的字符?
public static void main(String[] args) {
LinkedHashMap hm = new LinkedHashMap();
//HashMap hm=new HashMap();
String input = "ttaasjjikkk eee ";
input = input.trim();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
Integer val = (Integer) hm.get(c);
if (c != ' ') {//to exclude space count
if (val != null) {
hm.put(c, val + 1);
} else {
hm.put(c, 1);
}
}
}
System.out.println(hm);//each char count
Iterator itr = (Iterator) hm.keySet().iterator();
while (itr.hasNext()) {
Object temp = hm.get(itr.next());
String sTemp = temp.toString();
int value = Integer.parseInt(sTemp);
if (value == 1) {
System.out.println("First non repeated character is: " + hm.get(temp) + "," + temp);
return;
}
}
}
請幫助我,您的幫助將不勝感激。