Loading
notes intro/old submit AP Problems the dump links
 

Reading data in applications

 

THIS IS NOT PART OF THE AP SUBSET

Reading data into application can be accomplished by a variety of means. The book uses something called scanner classes, which is not to difficult. Again, you dont need to fully understand the class. We just need to be able to use it (this is called abstraction).

 

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 first have to create an instance of the Scanner. It probably makes sense to make it global(put it at the beginning of your class).

Scanner scan=new Scanner(System.in);

 

Now anywhere in your code where you want to read, you do one of 3 things:

 

  • String theReadString=scan.nextLine(); // This would read the next line as a String
  • int theReadInt=scan.nextInt(); // This would read the next line as an int
  • double theReadDouble=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.
 */

import java.util.Scanner;
public class TextReader
{
    Scanner scan=new Scanner(System.in);  //The Scanner constructor requires the use of the io class
    
  
    public void testOfScannerClass()
    {
        //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 a number");
        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);
        
    }  
    
    //main method for Eclipse
      public static void main(String[] args)
      {
            TextReader t=new TextReader();
            t.testOfScannerClass();
         
      }   
}