山東大學Java程式設計課程實驗報告4條件和迴圈語句__java

來源:互聯網
上載者:User
實驗目的:
熟悉布爾運算
熟練使用分支語句和迴圈語句控製程序執行流程
利用Swich語句實現多分支。

學習控制迴圈終止條件、迴圈的正常退出、使用 continue 語句、break 語句.

實驗步驟與內容:

1. 編寫一個程式,當鍵盤輸入“WASD”這四個按鍵中的一個(大小寫均可)時,輸出相對應的方向。(注意使用for 迴圈使程式更加人性化)

2. 從1-1000中隨機選取一個數,反覆讓使用者猜是什麼,直到使用者猜對或使用者退出為止。每猜一次告訴使用者猜測的結果是對或過大或過小。使用一個標示值確定使用者是否想退出。當使用者猜對時告訴他猜對的次數。每次遊戲結束時詢問使用者是否想繼續玩,直到使用者選擇結束。

package experiment4;import java.util.Scanner;public class HiLo {public static void main(String[] args) { int number=1,yournumber,i=1;String choice ="y" ;while (choice.equalsIgnoreCase("y")) {number=(int) (Math.random()*1000)+1;System.out.println("請輸入一個數字(1-1000)");Scanner scan=new Scanner(System.in);yournumber=scan.nextInt();if(yournumber>1000) {System.out.println("您輸入的數字不符合要求。請重新輸入");               yournumber=scan.nextInt();}while(yournumber<=1000&&number!=yournumber) {if(number>yournumber) {System.out.println("你輸入的數字小啦,請重新輸入");yournumber=scan.nextInt();i++;}if(number<yournumber) {System.out.println("您輸入的數字大啦,請重新輸入");yournumber=scan.nextInt();i++;}}if(number==yournumber) {System.out.println("恭喜您,猜中了。您共猜了"+i+"次就猜中啦。輸入Y繼續遊戲,N放棄遊戲");choice=scan.nextLine();choice=scan.nextLine();}}}}
package experiment4;import java.util.Scanner;public class WSAD {public static void main (String [] args) {System.out.println("請輸入WSAD中的一個");Scanner scan=new Scanner(System.in);String str;str=scan.nextLine();Boolean play = str.equalsIgnoreCase("W")|str.equalsIgnoreCase("S")|str.equalsIgnoreCase("A")|str.equalsIgnoreCase("D");while(true) {while(play) {if (str.equalsIgnoreCase("W"))System.out.println("上");if (str.equalsIgnoreCase("S"))System.out.println("下");if (str.equalsIgnoreCase("A"))System.out.println("左");if (str.equalsIgnoreCase("D"))System.out.println("右");System.out.println("請輸入WSAD中的一個");str=scan.nextLine();play = str.equalsIgnoreCase("W")|str.equalsIgnoreCase("S")|str.equalsIgnoreCase("A")|str.equalsIgnoreCase("D");}while(!play) {System.out.println("您輸入的不符合要求,請重新輸入WSAD中的一個");str=scan.nextLine();play = str.equalsIgnoreCase("W")|str.equalsIgnoreCase("S")|str.equalsIgnoreCase("A")|str.equalsIgnoreCase("D");}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.