Thứ Bảy, 21 tháng 4, 2012

Bài 3 – Biến trong Java



import java.io.*;
public class Hello {
                public static void main(String[] args) throws Exception {
                                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                                System.out.print("Nhap a: ");
                                int a = Integer.parseInt(in.readLine());
                                System.out.print("Nhap b: ");
                                int b = Integer.parseInt(in.readLine());
                                int ketqua;
                                ketqua = a+b;
                                System.out.println("Ket qua bai toan a+b la: “ + ketqua);
                }
}


Nhập thử 2 số a và b vào đi bạn, kết quả bài toán a+b sẽ được in ra.
*Lí thuyết:
import java.io.*;
public class Hello {
                public static void main(String[] args) throws Exception {
                                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                                System.out.print("Your name is: ");
                                String str;
                                str = in.readLine();
                                System.out.println("Welcome " + str + " to Java");
                }
}

Tạm thời, trong chương trình này, bạn chỉ nên quan tâm đến dòng
String str khai báo biến str kiểu chuỗi, và

System.out.println("Welcome " + str + " to Java")

Đây cũng là dòng System.out.println như chương trình đầu, có khác là + str + tức là đưa một biến vào chuỗi in ra. Chỉ đến đó thôi nhé, sau đó, hãy quan tâm đến bài hôm nay
System.out.print("Nhap a: ");
int a = Integer.parseInt(in.readLine());
System.out.print("Nhap b: ");
int b = Integer.parseInt(in.readLine());
int ketqua;
ketqua = a+b;
System.out.println("Ket qua bai toan a+b la: “ + ketqua);

Giải thích
import bạn nhập class hay thư viện chuẩn, tạm thời đừng quan tâm nó là gì, chỉ cần nhớ là có nó để chương trình chạy
System.out.print in ra một chuỗi, nhưng không xuống dòng
System.out.println in ra một chuỗi, nhưng xuống dòng
int ketqua tức là khai báo biến ketqua kiểu int
ketqua = a+b tức là gán kết quả một biểu thức tính toán (ở đây là biến a + biến b ) cho biến ketqua
System.out.println("Ket qua bai toan a+b la: “ + ketqua) thì đơn giản rồi, in cái dòng đó ra, chỉ khác là nó đưa biến ketqua của bạn vào chuỗi đó. 



nguồn: http://forum.cuasotinhoc.vn
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 nhận xét

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© Download do an khoa luan tai lieu
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0
Posts RSSComments RSS
Back to top