Question

i am supposed to create a program which keeps reading user input from the command line until the user types quit I shall also use the indexOf to get the position of all space characters.

I tried following:

import java.util.Scanner; 
import java.lang.String;
public class Aufgabe6b {

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);

        String a;
        System.out.println("Bitte Eingabe machen!");
        while(true){

            a=scanner.nextLine();
        if("quit".equals(a)){
            break;
        }
        }
        System.out.println(a.indexOf(" "));
    }
}

While a.indexOf is only giving me the position of the first " " it founds, i still have an issue with the scanner and the quit.

If i type:

Hello this is a test quit, it doesnt quit. if i type just quit, it breaks of the queue. if i type quit hello this ist a test, i doesnt quit.

I am supposed only to use indexOf and the Scanner as well as the nextLine method. Is this possible, what did i wrong?

Was it helpful?

Solution

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);
        }

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top