One of the main problem is that you're using s.next()
instead of s.nextLine()
: the difference between the two method is that Scanner.next()
, I quote Java documentation,
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Scanner.nextLine()
, instead,
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Beyond that, when you create a scanner, you have to remind to always close it when you finished, because it cause a memory leak if you aren't using it anymore. Also, I strongly suggest to use, whenever you have to compare two strings, the equals()
method, but in this specific case you can also use the more practical isEmpty()
. I suggest you delve into the subject by reading this awesome answer on the topic and the String documentation.
In conclusion the code should be something like this:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
LinkedHashMap<String,Integer> hm = new LinkedHashMap<String,Integer>();
while(true){
String a=s.nextLine();
if(a.isEmpty())
break;
else if(!hm.containsKey(a))
hm.put(a,1);
else
hm.put(a,hm.get(a)+1);
}
s.close();
System.out.println(hm);
}