Using Scanner objects to parse strings and read input from the

Download Report

Transcript Using Scanner objects to parse strings and read input from the

Strings as objects
• Strings are objects. Each String is an instance of
the class String
• They can be constructed thus:
• String s = new String("Hi mom!");
• Strings are so common, Java provides a handier
way of creating them:
• String s = "Hi mom!";
• Strings have methods: loads of them!!!
Some methods for Strings
String s1 = "harry";
String s2 = "harold";
if ( s1.equals(s2) )
System.out.println("Strings are the same");
if ( s1.compareTo(s2) < 0 )
System.out.println(s1 + "...." + s2);
else
System.out.println(s2 + "...." + s1);
Comparing Strings
• s1.compareTo("hi mom!")
• returns a value < 0 if this s1 is ordered
before "hi mom"
• returns a value > 0 if "hi mom" is ordered
before s1
• returns 0 if they are the same
• Ordering is called lexicographic order
String concatenation
• String s1 = "Hi" + " mom";
• String s2 = "your lucky number is "
+ number;
• String s3 = s1.concat(s2);
• String s3 = s1 + s2;
A number will be first turned into a String, then concatenated.
Substrings
• A String is stored as an array of characters:
character:
index:
H
i
_
M
o
m
!
0
1
2
3
4
5
6
• public String substring(int beginIndex)
• public String substring(int beginIndex, int endIndex)
Other String methods
• return the character at a given index:
– public char charAt(int index)
• get the length of a String:
– public int length()
Processing string contents: Scanner
All the strings we’ve seen before have been short (a word or two).
To process long strings (such as sentences) we need to be able to split
up strings into their parts (words, numbers, etc.).
The parts of a sentence are called tokens.
We can use the java.util.Scanner class to create Scanner
objects which go through a string “scanning” for tokens.
token
token
token token
token token token token
token
“This is a string with 9 tokens in it.”
How do we recognise tokens? They are separated by delimiters
(in the sentence above, blank spaces).
Using a scanner object to read words from a string
// start with Import java.util.Scanner;
String s = “I know lots of words”;
Scanner myScanner = new Scanner(s);
int wordcount = 0;
while(myScanner.hasNext()){
System.out.println(myScanner.next());
wordcount++;
}
System.out.println(wordcount+“ words in total”);
Objects from the Scanner class hold a stream of input from some
source, and scan the stream for the next string, int, line, etc
To use a scanner, we first create a new scanner object and give it the
thing we want it to scan. The new scanner object holds that source
inside itself.
We use methods inside that scanner object we created to get the next
string: myScanner.next(), int: myScanner.nextInt() etc.
System.out and System.in
• System.out is a static object in the System class that
links to output to the console.
• We can use methods contained in this out object to
print things on the console:
• System.out.println(“hello!”);
• The System class also contains a static object
System.in that links to input from the console.
• We can read input from System.in, but we must use
a Scanner object to do it.
Using the scanner class to read
System.in input from the console
• System.in has minimal set of features–it can
only read one byte at a time
• In Java 5.0, the Scanner class was added to read
input in a convenient manner
in = new Scanner(System.in);
• Scanner
System.out.print("Enter quantity: ");
int quantity = in.nextInt();
• nextDouble() reads a double
• nextLine() reads a line (until user hits Enter)
• next() reads a word (until any white space)
Using a scanner object to read from input
import java.util.Scanner;
class testScanner{
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = myScanner.next();
System.out.print("Enter your age: ");
int age = myScanner.nextInt();
System.out.println("hello "+name+" ("+age+")");
}
}
Objects from the Scanner class hold a stream of input from some
source, and scan the stream for the next string, int, line, etc
To use a scanner, we first create a new scanner object and give it the
source stream we want it to scan.
The new scanner object holds that source stream inside itself.
We use the methods inside the scanner object we created to get the
next string: myScanner.next(), int: myScanner.nextInt() etc.
Some methods in the Scanner class
• public Scanner(String x)
– Constructs a new scanner object and gives it a String to scan. The newly created
object will return words (or other tokens) out of that string.
• public Scanner(InputStream x)
– Constructs a new scanner object and gives it a stream of input to scan. The new
object will return words (or other tokens) out of that input stream.
• public Scanner(File x)
– Constructs a new scanner object and gives it a File to scan. The newly created object
will return words (or other tokens) out of that File.
• public String next()
– Takes the next string (ending with a space) from x and returns it.
• public boolean hasNext()
– Returns true if there is something left to read from the scanner
• public int nextInt()
– Takes the next thing from stream x, converts it to an int, and returns it.
• public boolean hasNextInt()
– Returns true if there is an int to read from the scanner
•public Double nextDouble()
•public String nextLine()
•public boolean hasNextDouble()
•public boolean hasNextLine()
Using scanner
• We can construct scanner objects to scan Strings, input from
System.in, and files (we’ll learn about scanning files later).
• This is because the scanner class has different constructors for
each of those types of input.
• Once we’ve created a scanner object for some input, we can get
strings, ints, doubles, or whole lines from that object, using the
relevant scanner methods on that object.
• We can also check, before we get any of those, whether there is
actually a string, int, double or line to get (again, using the relevant
“hasNext” methods).
• The best place to learn about scanner objects is on the Java api
website. Go to http://java.sun.com/j2se/1.5.0/docs/api/
and search for scanner in the “all classes” window on the lower left