Session 1 |
Scanner
Input and output (I/O) operations are very complicated, both at the software and at the hardware level. Part of the problem is that the way in which data is organized outside the computer is different from the way it is organized inside the computer. Lots of computation is needed to convert data between various forms. Luckily, most of the complication has been hidden inside methods that our program can use.
In this session, we will use methods of the class java.util.Scanner
for input. Scanner is not a part of the fundamental Java language, but is part of a package java.util
that we can include in our program. A package is a collection of classes which can be used in any program.
After Python, it may seem odd that Java does not have I/O built into it. The reason for this is that there are lots of different ways to get input from users – keyboards, mice, touch screens, speech, etc. Java uses different classes of objects to handle this variety of different input mechanisms, and Java allows the programmer to pick the right I/O package for the job.
Example:
//Import the package to work with the console input import java.util.Scanner; public class Data_Input { public static void main(String[] args) { //Create own Scanner object with a name (e.g. "scan") and //tell it to read text from the keyboard System.in Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); //Get a string from the input String userName = scan.nextLine(); System.out.println("Enter an integer"); //Get an integer from the input int myInt = scan.nextInt(); System.out.println("Enter a double"); //Get a double from the input double myDouble = scan.nextDouble(); System.out.println(userName + " your entered integer: " + myInt); System.out.println(" and double: " + myDouble); } }
Session 1 |