Introduction to programming in java Lecture 06 Input from keyboard
Introduction Picture taken from Book entitled Introduction to Programming in Java: An interdisciplinary approach
Introduction Picture taken from Book entitled Introduction to Programming in Java: An interdisciplinary approach
Input From Keyboard Java supports three standard input/output streams: System.in (standard input device), System.out (standard output device), and System.err (standard error device). The System.in is defaulted to be the keyboard; while System.out and System.err are defaulted to the console.
Input From Keyboard double i = scanner.nextDouble(); Java SE 5 introduced a new class called Scanner in package java.util to simplify formatted input. Instantiate a Scanner Scanner myScanner = new Scanner(System.in); Read an entire line of text we use nextLine(); String input = myScanner.nextLine(); Read an integer value we use nextInt() int i = scanner.nextInt(); Read floating valueinteger value we use nextDouble() double i = scanner.nextDouble();
Example # 1: Enter your name import java.util.Scanner; public class MyName { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter your full name: "); String name = in.nextLine(); System.out.println(“Wellcome Mr. " + name); }
Example 2: Get Student ID import java.util.Scanner; public class StudentID { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter your student ID : "); int id = in.nextInt(); System.out.println(“Your ID : " + id); }
Example 3: Product of 2 numbers import java.util.Scanner; public class Product { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter first number : "); double x = in.nextDouble(); System.out.print("Enter second number : "); double y = in.nextDouble(); double ans = x * y ; System.out.println( x + “ * “ + y + “ = " + ans); }
Example 3: Name and Age import java.util.*; public class NameAndAge { public static void main(String[] args) { int age; String name; Scanner in = new Scanner(System.in); System.out.println("Enter full name: "); name = in.nextLine(); System.out.println("How old are you? "); age = in. nextInt(); System.out.println(name + '\t' + age); }
Practice Questions Write a program called MyMath which first reads two integer values from the standard input and then compute sum , product, division and subtract of those two numbers and prints the result. For example > Java MyMath Enter 1st number: 10 Enter 2nd number: 5 Sum : 10 + 5 = 15 Minus: 10-5 = 5 Product: 10 * 5 = 50 Division: 10 / 5 = 2
Submission deadline of Assignment No. 1 is 24th Sep 2013 For details: See Lecture 05