Feb 12, 2012

[Java] keyboard(console) input (Scanner)

Scanner (input source)
    input source can be : (1) readable file,  (2) keyboard (System.in),  (3) string source


 // outside class
import java.util.*;
import java.io.*;  // to use file input

// inside method
// keyboard input
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();

// file input
File filename = new File("item.db");

Scanner sc = new Scanner(filename);
while(sc.hasNextInt())  {
        int item = sc.nextInt();
        System.out.println(item); }
sc.close();


--------------------------------------------------------------------------------------------------------------





Syntax highlighted by http://tohtml.com/java/


// Java
// console input (Scanner)

// input source can be : 
// (1) readable file,  (2) keyboard (System.in),  (3) string source


import java.util.*;
import java.io.*;  // to use file input, also include "throws IOException"

class scanner
{

 public static void main(String[] args) throws IOException
 {
        
        // keyboard input
        System.out.println("Input number between 1 and 5");
        Scanner scan = new Scanner (System.in);    
        
        while(!scan.hasNextInt())
        {
            scan.next();  // if input is not integer value, ignore it.
            System.err.println("Input should be integer value");
        }
        
        int input=scan.nextInt();  
        System.out.println("Input value = " +input);
 
            
        // String source input
        String source = "1 fish 5 fish red fish blue fish";     
        Scanner add = new Scanner (source).useDelimiter("\\s*fish\\s*");
        
        int n1 = add.nextInt(),  n2 = add.nextInt();
        System.out.printf("%d + %d = %d \n", n1, n2, n1+n2);
        System.out.println(add.next());
        System.out.println(add.next());
        
        
        // Input from a file with file name "item.db"
        // to use file input, 
        //    add "throws IOException" in main method declaration
        File filename = new File("item.db");
        
        // read line by line and print them
        //BufferedReader fln = new BufferedReader(new FileReader(filename));
        //String buf = fln.readLine();
        //while(buf != null)
            //System.out.println(buf);
        //fln.close();
        
        // read word by word and print them,  
        // nextInt() = int, next() = char
        Scanner sc = new Scanner(filename);
        while(sc.hasNextInt())  {
            int item = sc.nextInt();
            System.out.println(item);    }
        sc.close();
        
 }
}

No comments:

Post a Comment