JAVA基礎——編程練習(三),java基礎編程練習

來源:互聯網
上載者:User

JAVA基礎——編程練習(三),java基礎編程練習
熟悉String方法的使用之判斷檔案名稱是否合法

學習之餘,寫個小練習來鞏固一下String的方法應用。

任務:

1、判斷使用者選擇要輸入的內容的類型

2、如果是java檔案,輸出“您輸入的是java檔案名稱”

3、如果是郵箱地址,輸出“您輸入的是郵箱地址”

4、如果都不是,輸出“無法解析您輸入的內容”

代碼如下:

 1     public static void main(String[] args) { 2         Scanner in = new Scanner(System.in); 3         boolean flag = true; 4         do { 5             System.out.println("請您要判斷的內容:"); 6             String name = in.next(); 7  8             switch (Jude(name)) { 9             case 1:10                 System.out.println("您輸入的是java檔案名稱");11                 flag = false;12                 break;13             case 2:14                 System.out.println("您輸入的是郵箱地址");15                 flag = false;16                 break;17             case -1:18                 System.out.println("無法解析您輸入的內容,請重新輸入!");19                 break;20             }21         } while (flag);22         in.close();23     }24 25     /*26      * 判斷格式27      */28     private static int Jude(String Name) {29 30         int count1 = 0;// 字串中包含.的個數31         int count2 = 0;// 字串中包含@的個數32 33         for (int i = 0; i < Name.length(); i++) {// 統計個數34             if (Name.charAt(i) == '.') {35                 count1++;36             }37             if (Name.charAt(i) == '@') {38                 count2++;39             }40         }41         if (count1 == 1 && count2 == 1) {42             // 擷取郵箱中"@"符號的位置43             int index2 = Name.indexOf('@');44             // 擷取郵箱中"."號的位置45             int index3 = Name.indexOf('.');46             if (index2>0 && index3-index2> 1&&index3!=Name.length()-1) {// 判斷必須包含"@"符號,且"@"必須在"."之前47                 48                 return 2;49             }50         }51         if (count1 > 0) {52             // 擷取檔案名稱中最後一次出現"."號的位置53             int index = Name.lastIndexOf('.');54             // 擷取檔案的尾碼55             String prefix = Name.substring(index);56             57             // 判斷必須包含"."號,且不能出現在首位,同時尾碼名為"java"58             if (index != -1 && index != 0 && prefix.equals(".java")) {59 60                 return 1;61             }62         }63         return -1;64 65     }

運行結果:

這是按照我自己理解寫的小程式,主要是用來熟悉String類的方法的使用,可能有很多需要改進的地方,如果有錯誤的地方請指出來謝謝!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.