Question

The user will enter a=(number here). I then want it to cut off the a= and retain the number. It works when I use s.next() but of course it makes me enter it two times which I don't want. With s.nextLine() I enter it once and the delimiter does not work. Why is this?

    Scanner s  = new Scanner(System.in);
    s.useDelimiter("a=");
    String n = s.nextLine();
    System.out.println(n);
Was it helpful?

Solution

Because nextLine() doesn't care about delimiters. The delimiters only affect Scanner when you tell it to return tokens. nextLine() just returns whatever is left on the current line without caring about tokens.

A delimiter is not the way to go here; the purpose of delimiters is to tell the Scanner what can come between tokens, but you're trying to use it for a purpose it wasn't intended for. Instead:

String n = s.nextLine().replaceFirst("^a=","");

This inputs a line, then strips off a= if it appears at the beginning of the string (i.e. it replaces it with the empty string ""). replaceFirst takes a regular expression, and ^ means that it only matches if the a= is at the beginning of the string. This won't check to make sure the user actually entered a=; if you want to check this, your code will need to be a bit more complex, but the key thing here is that you want to use s.nextLine() to return a String, and then do whatever checking and manipulation you need on that String.

OTHER TIPS

Try with StringTokenizer if Scanner#useDelimiter() is not suitable for your case.

Scanner s = new Scanner(System.in);
String n = s.nextLine();
StringTokenizer tokenizer = new StringTokenizer(n, "a=");

while (tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

or try with String#split() method

for (String str : n.split("a=")) {
    System.out.println(str);
}

input:

a=123a=546a=78a=9

output:

123
546
78
9
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top