|
Scanner class - to input data - API
Reading data in applications
Import
You will need to import the proper class. To import means to include
other Classes so that we can use them. Some classes like the Math
class we dont need to import because it is so common that is it
imported (included automatically). But we will need to import the
Scanner class. Which is located in the java.util package. (A package
is a set of classes bundled together).
to use the Scanner, we import:
import java.util.Scanner;
Now in our code we need to declare and initialize the Scanner (which
I have called scan).
Scanner scan=new Scanner(System.in);
Now anywhere in your code where you want to read, you do one of
3 things:
- String theInputtedString=scan.nextLine();
// This would read the next line as a String
- int theInputtedInt=scan.nextInt();
// This would read the next line as an int
- double theInputtedDouble=scan.nextDouble();
// This would read the next line as a double
An example is included below:
/*
* This simple class is to test the Scanner class' ability to read user input.
*/
//you need to import the scanner in order to use it
import java.util.Scanner;
public class TextReader
{
public void testOfScannerClass()
{
//You need to initialize the scanner in order to use it
Scanner scan=new Scanner(System.in);
//test of reading Strings
System.out.println("Type in a string");
String theString=scan.nextLine();
System.out.println("In case you forgot, you just typed " + theString);
//test of reading int
System.out.println("Type in an integer");
int theInt=scan.nextInt();
System.out.println("In case you forgot, you just typed " + theInt);
//test of reading double
System.out.println("Type in a decimal");
double theDouble=scan.nextDouble();
System.out.println("In case you forgot, you just typed " + theDouble);
}
//Create a method that will ask your name and age and then
// find how many years older mr borland is then you (im 33)
//it will spit out Mr Borland is 15 yrs older than Charlie
public void ageDiff()
{
//YOUR CODE GOES HERE
}
//Create a method that will convert meters to centimeters and also inches.
//It will ask for meters and then print out the number of cms and inches
public void convertMeters()
{
//YOUR CODE GOES HERE
}
}
|