Reading Data from Keyboard
කලින් ලිපියේදී අපි output ගැන සාකච්චා කලා.
System.out.println() // produce output to the screen
දැන් අපි බලමු කොහොමද inputs අරගන්නේ කියලා.
System.in – to get input from the keyboard
මෙහිදී අපි Scanner Class එක භාවිතා කල යුතයි. Scanner class එක java හි තිබෙන class එකක් නිසා අපි එය භාවිතයට ගැනීමට පෙර එය අපේ programme එකට import කර ගත යුතුයි.
import java.util.Scanner;
මෙම code එක අපේ programme එකට add කිරීම මගින් Scanner class එක අපේ programme එකට add කර ගත හැක.
දැන් අපි බලමු කොහොමද scanner එක use කරන්නේ කියලා.
Scanner sc = new Scanner(System.in);
මෙම code එක මගින් සිදුවන්නේ new scanner object එකක් sc යන නමින් initialize වෙන එක.
දැන් අපි බලමු කොහොමද අපේ scanner එකට data input කරන්නේ කියලා.
int marks; //initialize variable Scanner input = new Scanner(System.in); //initialize Scanner marks = input.nextInt(); //save user value into the variable
marks = input.nextInt(); මෙහිදී අපි nextInt යොදාගත්තේ අපි ලබා දෙන input එක integer එකක් නිසා. අපි ලබා දෙන input එක String (text) එකක නම් අපි nextInt() වෙනුවට nextLine යන්න යොදාගත යුතුය.
දැන් අප ලබාදුන්නු input එක marks කියන variable එකේ තාවකාලිකව ගබඩා වී ඇත. දන් අපිට එය අපේ programme එකේ භාවිත කල හැක.
name=sc.nextLine(); System.out.println("Hello "+name); //Print Hello + User input
Full example code
import java.util.Scanner; class input{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); String name; System.out.println("Enter your name"); name=sc.nextLine(); System.out.println("Hello "+name); sc.close(); } }