CSCI 201
Introduction to Algorithm Design home | homework index | labs index |
FALL 2006 |
if-else
statements, and while
loops. You will also use
some basic input methods of the Scanner
class and some formatting
techniques of the printf
method.
Scanner is a class that is built-in to Java (starting with Java version 1.5).
It is located in the java
.util
package. Scanner
has several methods.
Some methods
for inputting primitive values are:
To input Strings you can use:
To check if there are still more tokens left you can use:
The following code segment demonstrates all the above methods.
Scanner input = new Scanner(System.in); int i; double x; String word; String line; String theRest = "no input"; System.out.print("Enter int, double, word, line: "); i = input.nextInt(); x = input.nextDouble(); word = input.next(); // returns a String up to next whitespace line = input.nextLine(); // returns the rest of line , excluding any line separator at the end System.out.printf("Integer: %d\nDouble: %f\nWord: %s\n Line: %s\n", i, x, word, line); if (input.hasNext()){ theRest = input.nextLine(); } System.out.printf("Also entered: %s", theRest);
If end-of-file is the next input value after the line, output will be:
Enter int, double, word, line: 4 5.7 Textbook for CSCI201 Integer: 4 Double: 5.700000 Word: Line: Textbook for CSCI201 end-of-file Also entered: no input
Complete String API available at http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html. Some methods are:
For example, to make variable alpha
equal to the fifth character
from String word
, you need to write:
char alpha = word.charAt(4);
Note: Remember that characters are numbered starting at 0, so the fifth
character really is at position 4.