Java Random Part 3 Important
Java Random Part 3 Important
Example 1
public class CharacterTypes {
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter a line: ");
String line = kb.nextLine();
// characters are examined one-by-one
for (int i = 0; i < line.length(); i++){
char c = line.charAt(i);
if( Character.isLetter(c) )
System.out.println(i+"\t"+c+"\t\tletter");
else if( Character.isDigit(c) )
System.out.println(i+"\t"+c+"\t\tdigit");
else
System.out.println(i+"\t"+c+"\t\tother");
}
}
}
11
Character class
Example 2
public class SumNumericValues
13
Character class
Example 3
public class ValidateStudentNumber
No instance of Character is used which means the methods are called using
statements of the form
If ( ! Character.isDigit(c) ) valid = false ;
14
Character class
Example 3
public class ValidateStudentNumber
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter a number: ");
String number = kb.next();
// characters are examined one-by-one
boolean valid = true;
for (int i = 0; i < number.length(); i++){
char c = number.charAt(i);
if(! Character.isDigit(c) ) valid = false;
}
if (valid) System.out.println("Valid");
else System.out.println("Invalid");
}
}
15
Scanner class
The Scanner class is useful when you need to parse some stream that
is said to contain tokens.
We can easily create a Scanner object that is associated with one of:
– System.in
– a string Streams containing tokens
– a file
Examples
Scanner s = new Scanner(System.in);
Scanner s = new Scanner(s); //s is of type String
Scanner s = new Scanner(f); //f is of type File
16
Scanner class
Scanner methods
17
Scanner class
Examples
18
Scanner class
Example 1
public class DisplayReadme
The file Readme.txt is read, line-by-line, until there are no lines left.
A Scanner object is needed to provide a reference to the file and the current
location in the file. Consider the statement:
Scanner f = new Scanner( new File("Readme.txt"));
19
Scanner class
Example 1
20
Scanner class
Example 2
public class ScanString
A Scanner object is needed that provides a reference to the file and the current
location in the file. Consider the statement:
String token = s.next() ;
21