返回列表 發帖

TQC210 - 字元搜尋器

本帖最後由 tonyh 於 2013-7-27 17:29 編輯
  1. import java.util.Scanner;
  2. public class tqc210
  3. {
  4.     public static void main(String args[])
  5.     {
  6.         Scanner s=new Scanner(System.in);
  7.         System.out.println("請輸入字串");
  8.         String str=s.nextLine();
  9.         System.out.println("請輸入要搜尋的字元或字串");
  10.         String str1=s.nextLine();
  11.         int loc=-1;    //位置的初始值
  12.         boolean find=false, find1=false;
  13.                /* boolean 變數的值只有兩種 true 或 false
  14.                   find 變數用來控制 "第幾個位置找到了" 的出現
  15.                   find1 變數用來控制 "搜尋的字元不在字串中" 的出現 */
  16.         do
  17.         {
  18.             loc=str.indexOf(str1,loc+1);
  19.             if(loc>-1)
  20.             {
  21.                 if(!find)   //等同於 find=false
  22.                 {
  23.                      System.out.println("第幾個位置找到了");
  24.                      find=true;
  25.                 }
  26.                 find1=true;
  27.                 System.out.println(loc+1);
  28.             }
  29.         }while(loc!=-1);
  30.         if(!find1)
  31.             System.out.println("搜尋的字元不在字串中");
  32.     }
  33. }
複製代碼

返回列表