2017 - 10 -18 常見對象 Scanner String

java 引用  https://www.zhihu.com/question/31203609
c++引用和java引用   http://blog.csdn.net/waitforfree/article/details/51030013
java的引用和c++的指針更像

1 Scanner(jdk 5之後)
(1)improt java.util.Scanner;
   Scanner sc = new Scanner(System.in);//標準的輸入流,對應着鍵盤錄入。
   System類下有一個靜態的字段:
             public static final InputStream in;
   InputStream is = System.in;
  例如: 
  class Demo(){
         public static final int x =10;
         public static final Student s =new Student();
}
   int y = Demo.x;
   Student s = Demo.s;
--------------------
   因此用的構造方法:
      Scanner(InputStream source)
---------------------
(2)nextInt()  一個基本用法
   int x = sc.nextInt();
   System.out.println("x:"+x);
(3) 基本格式
  public boolean hasNextXxx();判斷是否是某種類型的元素
  public Xxx  nextXxx(); 獲取該元素
  舉例:用int類型的方法舉例
  public boolean hasNextInt();
  public int nextInt();
  
  注意:InputMismatchException:輸入的和你想要的不匹配
 
  //獲取數據 int類型
  Scanner sc = new Scanner(System.in);
  if(sc.hasNextInt()){
        int x =sc.nextInt();
        System.out.println("x:"+x);
     }else{
        Systme.out.println("你輸入的數據有誤!")
   }
      
(4) 常用的兩個方法:
    public int nextInt():獲取一個int類型的值
    public String nextLine():獲取一個String類型的值
     Scanner sc = new Scanner(System.in);
      int a = sc.nextInt();
      int b = sc.nextInt();
      String s1 = sc.nextLine();
      String s2 = sc.nextLine();
     a:獲取一個int類型的值,再獲取一個int類型的值
     b:獲取一個string類型的值,再獲取一個string類型的值
     c: 獲取一個string類型的值,再獲取一個int類型的值
   出現問題:
     d:先獲取一個int數值,在獲取一個字符串時,出現了一個小問題。
      int a = sc.nextInt();
      String s1 = sc.nextLine();
      System.out.println("a:"+a+",s1"+s1);
      //打算輸入10 a 結果只輸入了10 程序就輸出了 輸出10
   如何解決?
     A:先獲取一個數值後,再創建一個新的鍵盤錄入對象獲取字符串。
              (但會創建許多對象)
     B:把所有的數據都先按照字符串獲取,然後要什麼,就對應的轉換成什麼
                   String line =sc.nextLine();

2 String類  最常見的類。。。沒有之一。。。

**可以直接賦值,java語法就這麼規定的。 
因爲String類太常用了,這樣直接賦值,避免多次創建內容相同的String對象,節省空間,提高效率。 

A:字符串:就是由多個字符組成的一串數據,也可以看成是字符數組
  通過查看API,我們可以知道
        a:字符串字面值"abc"也可以看成是一個字符串對象。
        b:字符串是常量,一旦被賦值,就不能被改變。

B:構造方法 6種
public String()       //空構造
public String(byte[] bytes)      //把字節數組轉成字符串
public String(byte[] bytes,int offset,int length)  //把字節數組的一部分轉成字符串
public String(char[] value)      //把字符數組轉成字符串
public String(char[] value,int offset,int count)   //把字符數組的一部分轉成字符串
public String(String original)     //把字符串常量值轉成字符串

C:字符串的方法
      public int length():返回此字符串長度

D: 練習
    byte[] bys = {97,98,99,100,101};
    String s2 = new String(bys);
    System.out.println("s2:"+s2);
    System.out.println("s2.length():"+s2.length());
     //輸出 abced 5
     //把字節數組轉換成字符串 ,97對應的ASCII值就是a
   
    //把字節數組的一部分轉成字符串 例如 得到字符串bcd
    String s3 = new String(bys,1,3);
    System.out.println("s3:"+s3);
    System.out.println("s3.length():"+s3.length());
    // 輸出bcd 3
    
3 String 的特點 一旦被賦值就不能被改變

  但是,字符串直接賦值,會先去字符串常量池裏面去找,如果有就直接返回,沒有,就創建並返回。。。
  一旦被賦值就不能被改變。。。。值不能變,並不是說引用不能變
 
  String s = "hello"
  s+= "world";
  System.out.println("s:"+s)//helloworld

  //無法改變hello 以及world 的值



***4 面試題
   String s1 = new String("hello")
   String s2 = "hello";  //這兩個的區別
**--------------------
==:比較引用類型比較的是地址值是否相同
equals:比較引用類型默認也是比較地址值是否相同,而String類重寫了equals()方法,比較的是內容是否相同。
---------------------
   System.out.println(s1 == s2);//false
   System.out.println(s1.equals(s2));//true
---------------------
  有區別,前者會創建2個對象,後者創建1個對象。

***4+ 面試題2
   A:
      String s1 = new String("hello");
      String s2 = new String("hello");
      System.out.println(s1 == s2);      //false
      System.out.println(s1.equals(s2));  //true
  
      String s3 = new String("hello");
      String s4 = "hello";
      System.out.println(s3 == s4);      //false
      System.out.println(s3.equals(s4));  //true

      String s5 = "hello";
      String s6 = "hello";
      System.out.println(s5 == s6);       //true
      System.out.println(s5.equals(s6));  //true
   B:
      String s1 = "hello";
      String s2 = "world";
      String s3 = "helloworld";
      System.out.println(s3 == s1 +s2);       //true
      System.out.println(s3.equals(s1+s2));    //true
      System.out.println(s3 == "hello" + "world");       //false  這個做錯了,應該是true
      System.out.println(s5.equals("hello"+"world"));  //true

   **字符串如果是變量相加,先開空間,再拼接

   **字符串如果是常量相加,是先加,然後在常量池找,如果有就直接返回,否則,就創建。


***5 String的判斷功能 6種
    boolean equals(Object obj):比較字符串內容是否相同
    boolean equalsIgnoreCase(String str):比較字符串內容是否相同,忽略大小寫
    boolean contains(String str):判斷大字符串中是否包含小字符串
    boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭
    boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾
    boolean isEmpty():判斷字符串內容是否爲空

    注意:字符串內容爲空,和字符串對象爲空。
          String s = "";
          String s = null;

***6 String 的獲取功能 8種
   
   索引,開頭第一個字符爲0。  
   找不到的返回索引爲 -1。
  
   int length():獲取字符串的長度
   char charAt(int index):獲取指定索引位置的字符
   int indexOf(int ch):返回指定字符在此字符串中第一次出現的索引----爲什麼這裏是int類型而不是char類型?----原因是'a'和97其實都可以代表'a'
   int indexOf(String str):返回指定字符串在此字符串第一次出現的索引
   int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置後第一次出現的索引
   int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置後第一次出現的索引
   String substring(int start):從指定位置開始截取字符串,默認到末尾結束------包含start這個字符
   String substring(int start,int end):從指定位置開始到指定位置結束截取字符串-----包括start,但是不包括end索引

7  字符串練習
(1)字符串的遍歷
  需求:遍歷獲取字符串中的每一個字符
  分析:
         A:如何能夠拿到每一個字符呢?
           char charAt(int index)
         B: 怎麼知道字符到底有多少個呢?
            int length()
    
    for(int x=0;x<s.length();x++){
          //char ch = s.charAt(x);
          //System.out.println(ch);
            System.out.prinln(s.charAt(x));
}
(2)統計大小寫以及數字字符的個數
    案列:"Hello123World"
    結果: 大寫字符:2個
           小寫字符:6個
           數字字符:3個
    分析: 
           A:定義三個統計變量
               bigCount = 0
               smallCount = 0
               numberCount = 0
           B:遍歷字符串,得到一個字符
               length()和charAt()結合
           C:判斷該字符到底是屬於那種類型的
                通過ASCII碼錶
                  0 48
                  A 65
                  a 97
         雖然,我們按照數字的這種比較是可以的,但是,還有更加簡單的
                         char ch = s.charAt(x);
                         if(ch>='0'&&ch<='9') numberCount++
                         if(ch>='a'&&ch<='z') smallCount++
                         if(ch>='A'&&ch<='Z') bigCount++

***8 String 的轉換功能 7種
    byte[] getBytes():把字符串轉換成字節數組
    char[] toCharArray():把字符串轉換成字符數組
    static String valueOf(char[] chs):把字符數組轉換成字符串
    static String valueOf(int i):把int類型的數據轉成字符串
     //注意:String類的valueOf方法可以把任意類型的數據轉成字符串
    String toLowerCase():把字符串轉成小寫------本身沒變
    String toUpperCase():把字符串轉成大寫------本身沒變
    String concat(String str):把字符串拼接
----------------------------
    String s="JavaSE"
    byte[] bys = s.getBytes();   //打印出 74 97 118 97 83 69
    char[] chs = s.toCharArray();//打印出 J a v a S E
    String ss = String.valueOf(chs);// 打印出 JavaSE
    int i = 100;
    String sss = String.valueOf(i); //打印出100 不是整型了,而是字符串類型

    System.out.println(s.tolowerCase()); //javase
    System.out.println(s);               //JavaSE
    System.out.println(s.toUpperCase()); //JAVASE

9 字符串練習題2
A:把一個字符串的首字母轉成大寫,其餘爲小寫(只考慮英文大小寫字母字符)
  例如:helloWORLD
  結果:Helloworld
   //定義一個字符串
     String s = "helloWORLD";
   //先獲取第一個字符
     String s1 = s.substring(0,1);
   //獲取除了第一個字符以外的字符
     String s2 =s.substring(1);
   //把首字符轉成大寫
     String s3 = s1.toUpperCase();
   //把其餘轉成小寫
     String s4 = s2.tolowerCase();
   // 兩個拼接
     String s5 = s3.concat(s4);
   ---------------
   //優化後的代碼
   String result = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());
   System.out.println(result);

10 Strin類的其他功能
(1)替換功能:
    String replace(char old,char new)
    String replace(String old,String new)
(2)去除字符串兩端空格
   String trim()

   String s1 =" hello world "
   String s2 = s1.trim();
   System.out.println("---"+s1+"---");//--- hello world ---
   System.out.println("---"+s2+"---");//---hello world---
(3)按字典順序比較兩個字符串
   int compareTo(String str)
   int compareToIgnoreCase(String str)

   String s3 = "hello";
   String s4 = "hello";
   String s5 = "abc";
   String s6 = "xyz";
   System.out.println(s3.compareTo(s4)); //0  h-h
   System.out.println(s3.compareTo(s5)); //7  h-a
   System.out.println(s3.compareTo(s6)); //-16 h-x
  
   字符串第一個位置上不同的ascii相減的值

11 String類的compareTo()方法的源碼解析
   String s1 = "hello";
   String s2 = "hel";  
   System.out.println(s1.compareTo(s2)); // 2  爲什麼是2?
 
   回答:當都相同時,返回長度相減
  
   public int compareTo(String anotherString){
      //this -- s1 --"hello"
      //anotherString -- s2 --"hel"
     int len1 = value.length;//this.value.length--s1.toCharArray().length---5
     int len2 =anotherStirng.value.length;//s2.value.length --s2.toCharArray.length---3
     int lim = Math.min(len1,len2); //Math.min(5,3)----lim=3
     char v1[] = value;   //s1.toCharArray()
     char v2[] = anotherString.value; 
     //char v1[] = {'h','e','l','l','o'};
     //char v2[] = {'h','e','l'}
     int k = 0;
     while(k < lim){
      char c1 =v1[k];//c1 ='h'
      char c2 =v2[k];//c2 ='h'
      if(c1 != c2){
            return c1 -c2;
          }
        k++;
   }
   return len1- len2; // 5-3 =2;
}
      
12 字符串練習3
(1) 把數組中的數據按照指定格式拼接成一個字符串
   舉例:
         int[] arr ={1,2,3} 
   輸出結果:
            "{1, 2, 3}"
     
    //前提是數組已經存在
    int[] arr = {1,2,3};
    //定義一個字符串對象,只不過內容爲空
     String s ="";
    //先把字符串拼接一個"{"
     s+="{";
    //遍歷int數組,得到每一個元素
     for(int x=0;x<arr.length();x++){
         if(x == arr.length - 1){
              //就直接拼接元素和"}"
                s+=arr[x];
                s+="}";
            }else{
              //就拼接元素和逗號以及空格
                s+=arr[x];
                s+=", ";
          }
     }
      //輸出拼接後的字符串
      System.out.println("最終的字符串是:"+s)  //輸出{1, 2, 3}
      }
}
(2)字符串反轉
   舉例:
    輸入:"abc"
    輸出:"cba"

    Scanner sc =new Scanner(system.in);
    System.out.println("輸入一個字符串:");
    String line =sc.nextLine();

    //定義一個新字符串
    String result="";
    //把字符串轉成字符數組
    Char[] chs = line.toCharArray();
    //倒着遍歷字符串,得到每一個字符
    for(int x=chs.length-1;x>=0;x--){
             result +=chs[x];
        }
    //輸出新串
    System.out.println("反轉後的結果:"+result);
(3)統計大串中小串出現的次數
  舉例:
      字符串 "hehejavaheiheijavahahajavagunjavajavagun"
  輸出:java出現了5次

  思路:
      A:定義一個統計變量,初始化值是0。
      B:先獲取一次"java"在這個大串中第一次出現的索引
               如果索引值是-1,就說明不存在,返回統計變量
               如果索引值不是-1,就說明存在,統計變量++
      C:把剛纔的索引+小串的長度作爲起始位置,截取原始大串,得到一個新的字符串,並把該字符串的重新賦值給大串。
      D:回到B即可。
     publc static int getCount(String maxString,String minString){
          //定義一個統計變量,初始化值是0
          int count = 0;
          //先在大串中查找一次小串第一次出現的位置
          int index = maxString.indexOf(minString);
          //索引不是-1,說明存在,統計變量++
          while(index !=-1){
              count++;
          //把剛纔的索引+小串的長度作爲開始位置截取上一次的大串,返回一個新的字符串,並把該字符串的值重新賦值給大串
          int startIndex = index + minString.length();
          maxString = maxString.substring(startIndex);
          //繼續查
          index = maxString.indexOf(minString);      
         }
    return count;
}    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章