Reputation: 2130
Let me explain in detail, I kept googling about scanners and I can't fully understand what are scanners exactly. I read many articles but all of them say
The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions
quoted from the official website, most websites took it and non of them said what a scanner is in english
Let me illustrate.
I have 3 views, a Button
, EditText
,TextView
. I wanted to take the text from the EditView
and put it in the TextView
and I have 2 approaches, my question is what is the difference between them.
ALL THIS CODE GOES INTO THE ONCLICK LISTENER.
Scanner sc = new Scanner(editText.getText().toString());
String a = sc.next();
txv.setText(a);
and this
txv.setText(editText.getText().toString());
I got the data and it worked exactly the same in both cases and I can't seem to find anything useful.
Upvotes: 2
Views: 87
Reputation: 191844
You shouldn't be using Scanner here, you should be using StringTokenizer, or just split("\\s+")[0]
on the string.
But sc.next()
will read the first consecutive non-whitespace characters of the Scanner's input string into the variable a
, which gets set to the next textview.
For example
Scanner sc = new Scanner("hello world");
String s = sc.next(); // == "hello"
Otherwise, in CLI applications Scanner is used for interactive inputs. Doesn't have much other use cases in production code that I can think of. Even for reading files, BufferedReader or the NIO API would be preferred
Upvotes: 4