One option would be:
while(true)
{
a=scanner.nextLine();
int j = a.indexOf("quit");
if (j >= 0)
break;
}
If the word 'quit' is present, the indexOf
method will return a positive value.
The problem in your code is here: if("quit".equals(a))
For this condition to be true, 'a' must be exactly equal to "quit", comparing to any other string which is even slightly different will return false.
Hope this solves it :)
EDIT: To find number of occurences:
public static int OccurenceFinder(String source, String pattern) {
int counter = 0;
int index = source.indexOf(pattern);
if (index == -1) return 0;
counter++;
while (true) {
index = source.indexOf(pattern, index + 1);
if (index == -1) return counter;
counter++;
}
}
EDIT : to find positions
public static LinkedList<Integer> PositionFinder(String source, String pattern) {
LinkedList<Integer> list = new LinkedList<Integer>();
int index = source.indexOf(pattern);
if (index == -1) return list;
list.add(index);
while (true) {
index = source.indexOf(pattern, index + 1);
if (index == -1) return list;
list.add(index);
}
}