|
Scaner class, use the Get keyboard input.
public boolean DemoTest () {
Scanner input = new Scanner (System.in);
System.out.print ( "Please enter the student's name");
String name = input.next ();
int score = 0;
double sum = 0;
double average = 0;
for (int i = 0; i <5; i ++) {
System.out.print ( "Please enter [" + (i + 1) + "] course accomplishments");
score = input.nextInt ();
sum + = score;
}
average = sum / 5;
System.out.println ( "student" + name + "grade point average is" + average);
return true;
}
Use JUnit3 test code.
/ **
*
* /
package com.ch01;
import ch01.ScannerTest;
import junit.framework.Assert;
import junit.framework.TestCase;
/ **
*
* /
public class ScannerTestCase extends TestCase {
public void testch01Scanner () {
ScannerTest input = new ScannerTest ();
Assert.assertEquals (true, input.DemoTest ());
}
}
Detailed Scanner
java.lang.Object - >>> java.util.Scanner
All Implemented Interfaces - >>> Iterator
You can use a regular expression to parse simple text strings and basic types of scanners.
Scanner using delimiter mode its input into tokens, the default separator pattern and matches whitespace. You can then use the tag conversion method will be different next to the value of different types.
For example, the following code enables the user to read a number from System.in:
Scanner sc = new Scanner (System.in);
int i = sc.nextInt ();
As another example, the following code allows long types can be assigned from entries myNumbers file:
Scanner sc = new Scanner (new File ( "myNumbers"));
while (sc.hasNextLong ()) {
long aLong = sc.nextLong ();
}
The scanner can also use different from the blank separators. Here is an example of reading a number from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner (input) .useDelimiter ( "\\ s * fish \\ s *");
System.out.println (s.nextInt ());
System.out.println (s.nextInt ());
System.out.println (s.next ());
System.out.println (s.next ());
s.close (); output:
1
2
red
blue
The following code uses a regular expression simultaneously parse all four markers, and produces the same output of the above example:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner (input);
s.findInLine ( "(\\ d +) fish (\\ d +) fish (\\ w +) fish (\\ w +)");
MatchResult result = s.match ();
for (int i = 1; i <= result.groupCount (); i ++)
System.out.println (result.group (i));
S.CLOSE ();
The default whitespace scanner used to identify by Character.isWhitespace. Regardless of whether the previous change, reset () method will scanner delimiter value is reset to the default blank separator. |
|
|
|