දැනට තිබෙන පාඩම්...

Monday, August 17, 2015

ජාවා ඉගෙන ගනිමු - 3 පාඩම

යාලුවනේ අද අපි කථා කරන්නෙ ජාවා වලින් කෝමද input එකක් දෙන්නෙ කියලා

ජාවා වල තියෙන විශේෂත්වයක් තමයි ඒකෙ තියෙන libraries ගොඩ. ඒ වගේම අපි මේ input එක දෙන්න කලින් අපි java.util කියන library එක පිටින් ගෙන්න ගන්න ඕන.ඒ කියන්නෙ import කරන්න ඕන. ඒ library එකේ තමයි Scanner class එක තියෙන්නෙ.
import java.util.Scanner;

ඊලගට පුරුදු විදියට class එකේ නම ලියනවා.
class user_input

ඊලගට main method එක ලියනවා අපි.
ඒකට පස්සෙ අපි Scanner class එකෙන් object එකක් හදාගන්න ඕන. නැත්නම් මේ Scanner class එකෙන් කිසිම වැඩක් කරගන්න බෑ අපට.
Scanner මගේ = new Scanner(System.in);
මං හදපු object එකේ නම "මගේ".
මේ System.in කියන එකෙන් ජාවා වලට අපි කියනවා මේක තමයි System එකේ input එක කියලා.

ඊලගට අපිට input කරගන්න ඕන int type input එකක් නම්
int number1 = Integer.parseInt(මගේ.nextLine());

උඩින් තියෙන code එක තමයි command prompt එකේ ඔයාගෙ input එක හම්බෙනකන් බලං ඉන්න කඩ ඉර. හැබැයි ඔයා මේකෙ දෙන input එක එයා බලාපොරොත්තු වෙන data type එකේ නෙවෙයිනම් ඉතින් අන්තිමට error තමයි.

උඩින් තියෙන්නෙ int type input එකක් දෙන විදිහ. String එකක් input කරන්න දෙන විදිහ වෙනස්.
String name1 = මගේ.nextLine();



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

input දෙන්න පුලුවන් තව විදියක් කථා කරන්නයි යන්නෙ
කලින් Scanner class එක වගේම ඊලගට BufferdReader class එක ගැන

මේකෙත් කලින් වගේම අපි පිටින් import කරන්න වෙනවා library එක
import java.io*;

ඊලගට class එක ලියනවා
පුරුදු විදියට main method එක ලියනවා
අපි මේ class ඒකේදි එ්කට එන exceptions handle කරන්න වෙනවා, ඒ නිසා අපි main method එකත් එක්ක මෙහෙම ලියනවා.
public static void main(String args[])throws Exception

කලින් වගේ නෙවෙයි මේකෙ අපට objects 2ක් හදන්න වෙනවා.ඒ BufferedReader class, InputStreamReader class කියන දෙකෙන්
BufferedReader input= new BufferedReader (new InputStreamReader(System.in));

input කරන variable එක වෙනම declare කරන්නත් පුලුවන්
String name;
name = input.readLine();
System.out.println("My name is"+name);
මේකෙදි print වෙන්නෙ My name is ඔයා දුන්න input එක

ඒ වගේම String name = input.readLine(); කියන කොටසෙන් කරන්නෙත් උඩින් දක්වලා තියෙන ටිකමයි

int data type එකේදි Scanner class  එකේ වගේම වෙනස් වෙනවා
int  age= Integer.parseInt(input.readLine());

තවත් පාඩමක් අරන් ආයෙත් එන්නම් යාලුවනේ...





No comments:

Post a Comment

What is PowerShell -1

PowerShell mainly using by system administrators and system engineers to their daily work.  This task based command line mainly created by ...