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

Bài 8 – switch


Bạn đã học xong if. Bạn muốn dùng vòng lặp if để đánh giá điểm số nhập vào. Bạn sẽ viết chương trình sau đây

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 diem so: ");
                                int diem = Integer.parseInt(in.readLine());
                                if(diem<=2) System.out.println("Yeu");
                                if((diem>2) && (diem<=3)) System.out.println("Trung binh");
                                if((diem>3) && (diem<=4)) System.out.println("Kha");
                                if((diem>4) && (diem<5)) System.out.println("Gioi");
                                if(diem==5) System.out.println("Xuat sac");
                }
}


Thay vì lặp lại những câu if ấy, bạn nên dùng switch

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 diem so: ");
                                int diem = Integer.parseInt(in.readLine());
                                switch(diem)
                                {
                                                case 0:
                                                case 1:
                                                case 2:System.out.println("Yeu");break;
                                                case 3:System.out.println("Trung binh");break;
                                                case 4:
                                                case 5:System.out.println("Gioi");break;
                                                default:System.out.println("Vao sai");
                                }
                }
}


*break với switch: break sẽ thoát ngay ra khỏi khối lệnh trong thân của switch 
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