Ví dụ căn bản về thao tác đầu vào yêu cầu chương trình chạy lại. (The sample standard input to ask a user to run a program again.)






Đây là một bài tập về tư duy lập trình căn bản rất hay, các bạn mới học Java nên tham khảo. Đề bài yêu cầu bạn viết một chương trình nhập sự lựa chọn [yes/no], nếu bạn chọn [yes] chương trình sẽ tiếp tục hỏi bạn một lần nữa, còn chọn [no] thì sẽ thoát chương trình.




JavaExampleRunAgain.java
/**
 * @(#)JavaExampleRunAgain.java
 *
 * JavaExampleRunAgain application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/19
 */

import java.util.*;

public class JavaExampleRunAgain {
   
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
       
        while(true) {
            System.out.print("Are you run application again [yes/no]? ");
            String input = sc.nextLine();
            if(! input.equals("yes")){
                break;
               
            }
        }
       
        System.out.println(" \n \t -- VNLIVES.NET Goodbye you! See you later.");

    }
}

Khi chạy ứng dụng thao tác đầu vào của tôi sẽ 5 yes và 1 no, bạn sẽ thấy kết quả như sau:

Are you run application again [yes/no]? yes
Are you run application again [yes/no]? yes
Are you run application again [yes/no]? yes
Are you run application again [yes/no]? yes
Are you run application again [yes/no]? yes
Are you run application again [yes/no]? no

     -- VNLIVES.NET Goodbye you! See you later.





















No comments:

Post a Comment