JavaSE實戰——API(上) Eclipse使用、Object、Scanner、String、StringBuffer、StringBuilder、Integer、模擬用戶登錄案例

    轉載請聲明出處:http://blog.csdn.net/zhongkelee/article/details/46694955


說在前面

 

    熟話說,工欲善其事,必先利其器,首先,我們來看一下Eclipse這款IDE的使用技巧。接着依據JDK官方API來對String、StringBuffer類的成員方法進行介紹,並用來解決實際的幾個字符串問題。


Eclipse的使用技巧

    eclipse各種版本下載:http://www.eclipse.org/downloads/

    eclipse的編譯和運行環境配置:window -- Preference -- Java

    編譯環境:compiler 默認選中的就是最高版本。

    運行環境:installed JREs 默認會找你安裝的那個JDK。建議配置Java的環境變量。
    問題:
    低編譯,高運行,可以。
    高編譯,低運行,不可以。
    建議:編譯和運行的版本一致。

    Eclipse常用快捷鍵

    1.代碼自動補全:alt+/
    2.格式化:ctrl+shift+f
    3.導入包:ctrl+shift+o
        如果該類僅僅在一個包中有,就自己顯示了。
        如果該類在多個包中有,會彈出一個框框供你選擇。
    4.註釋:
        單行:ctrl+/,取消註釋再來一次。
        多行: ctrl+shift+/, ctrl+shift+\
    5.代碼上下移動:選中代碼 alt+上/下箭頭
    6.查看源碼:選中類名(F3或者ctrl+鼠標點擊)
    7.最大化窗口:ctrl+m
    8.編譯運行:ctrl+f11
    9.小叉幫助:ctrl+1


    提高開發效率:
    A:幫助我們自動提供構造方法:
          a:無參構造方法:在代碼區域右鍵--source--Generate Constructors from Superclass
          b:帶參構造方法:在代碼區域右鍵--source--Generate Constructors using fields..--finish
    B:成對的getXxx()和setXxx()方法
          在代碼區域右鍵--source--Generate Getters and Setters..
    C:快捷鍵:Alt+shift+s + 帶有下劃線的字母就可,如c、o、r、table、enter

    @Override-->是註解。這個註解的意思是說,該方法是重寫父類的。如果方法聲明和父類不匹配,就會報錯。

打Jar包和導入Jar包

    




    示例程序:

    所使用的Java工程--animal 實現代碼如下,寫完之後,按上述圖示進行打包,並將Jar包複製到另一個需要animal的工程中。步驟如上所示,記住導包後選擇Add to Build Path選項哦。

package ustc.lichunchun_01;

/**
 * 這是跳高接口
 * 
 * @author 李春春
 * @version V1.0
 */
public interface Jump {
	/**
	 * 這是跳高功能
	 */
	public abstract void jump();
}
package ustc.lichunchun_02;

/**
 * 這是動物抽象類
 * 
 * @author 李春春
 * @version V1.0
 */
public abstract class Animal {
	/**
	 * 這是吃飯的功能
	 */
	public abstract void eat();
	
	/**
	 * 這是睡覺的功能
	 */
	public abstract void sleep();
}
package ustc.lichunchun_02;

/**
 * 這是具體的貓類
 * 
 * @author 李春春
 * @version V1.0
 */
public class Cat extends Animal {

	@Override
	public void eat() {
		System.out.println("貓吃魚");
	}

	@Override
	public void sleep() {
		System.out.println("貓趴着睡覺");
	}
}
package ustc.lichunchun_02;

import ustc.lichunchun_01.Jump;

/**
 * 這是具體的狗類
 * 
 * @author 李春春
 * @version V1.0
 */
public class Dog extends Animal implements Jump {

	@Override
	public void jump() {
		System.out.println("會跳高的狗");
	}

	@Override
	public void eat() {
		System.out.println("狗吃肉");
	}

	@Override
	public void sleep() {
		System.out.println("狗站着睡覺");
	}

}
    測試代碼如下:

package ustc.lichunchun.animal.test;

import ustc.lichunchun_02.Animal;
import ustc.lichunchun_02.Cat;
import ustc.lichunchun_02.Dog;

public class AnimalDemo {
	public static void main(String[] args) {
		// 抽象類不能實例化
		// Animal a = new Animal();

		Animal a = new Cat();
		a.eat();
		a.sleep();

		System.out.println("--------------");

		a = new Dog();
		a.eat();
		a.sleep();

		System.out.println("--------------");
		
		// 想使用跳高功能
		Dog d = (Dog) a;
		d.eat();
		d.sleep();
		d.jump();
	}
}
Debug斷點調試

    Eclipse中代碼的高級(Debug)調試。作用:調試程序,查看程序執行流程。
    如何查看程序執行流程:要想看程序流程,就必須設置斷點。
    什麼是斷點:斷點就是一個標記,從哪裏開始。
    如何設置斷點:你想看哪裏的程序,你就在那個有效程序的左邊雙擊即可。
    在哪裏設置斷點:哪裏不會點哪裏。目前:我們就在每個方法的第一條有效語句上都加。
    如何運行設置斷點後的程序:右鍵 -- Debug as -- Java Application
    看哪些地方:
        Debug: 斷點測試的地方。在這個地方,記住F6,或者點擊也可以。一次看一行的執行過程。(Debug窗口,右上角三角形,show Debug toolBar)
        Variables: 查看程序的變量變化
        ForDemo: 被查看的源文件
        Console: 控制檯
    如何去斷點:
        a: 再次雙擊即可
        b: 找到Debug視圖,Variable界面,找到Breakpoints,並點擊,然後看到所有的斷點,最後點擊那個雙叉。


  Debug示例程序:

package ustc.lichunchun.args.demo;

/**
 * 通過debug查看程序執行流程
 *
 */
public class ArgsDemo {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		System.out.println("a: " + a + ", b: " + b);
		change(a, b);
		System.out.println("a: " + a + ", b: " + b);

		int[] arr = { 1, 2, 3, 4, 5 };
		change(arr);
		System.out.println(arr[1]);

	}

	public static void change(int a, int b) {
		System.out.println("a: " + a + ", b: " + b);
		a = b;
		b = a + b;
		System.out.println("a: " + a + ", b: " + b);
	}

	public static void change(int[] arr) {
		for (int x = 0; x < arr.length; x++) {
			if (arr[x] % 2 == 0) {
				arr[x] *= 2;
			}
		}
	}
}
Object類

    通過查閱API的java.lang.Object文檔,我們這裏主要介紹了Object類的hashCode()、getClass()、toString()、equlas()、clone()等方法,具體代碼如下。注意,子類一般複寫toString()、equlas()方法

package ustc.lichunchun.object.demo;

public class Student extends Object implements Cloneable{
	private String name;
	private int age;

	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	 /*
	 @Override
	 public boolean equals(Object obj) {
	 // 根據這裏比較的成員變量來決定返回true還是false
	 // 這裏其實要比較的就是name和age
	 //但是,name是String類型的,而String是引用類型,所以這裏不用==直接比較,否則比較的僅僅是地址值,s1!=s2,應該用equals()比較,使得s1==s2
	 // String的equals()方法是重寫自Object類的,比較的是字符串的內容是否相同。
	 // this - s1
	 // obj - s2
	 // 但是我們要使用的是學生類的特有成員變量,所以obj類要向下轉型
	 Student s = (Student) obj;// s -- obj -- s2
	 if (this.name.equals(s.name) && this.age == s.age)
	 return true;
	 else
	 return false;
	 }

	 @Override
	 public boolean equals(Object obj) {
	 if (this == obj)
	 return true;
	 if (!(obj instanceof Student))
	 return false;
	 Student s = (Student)obj;
	 return this.name.equals(s.name) && this.age == s.age;
	 }
	 */
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
package ustc.lichunchun.object.demo;

public class StudentDemo {

	public static void main(String[] args) {
		Student s = new Student();
		System.out.println(s.hashCode());//31168322
		System.out.println(s.getClass().getName());//ustc.lichunchun.object.demo.Student
		System.out.println("----------------------");
		
		/*
		 * toString()方法的值等價於:
		 * getClass().getName() + '@' + Integer.toHexString(hashCode())
		 * this.getClass().getName() + '@' + Integer.toHexString(this.hashCode())
		 * toString()返回值沒有意義,一般都需要重寫toString()方法
		 * 只要把該類的所有成員變量值組成返回即可。
		 * 最終版方案就是自動生成toString()方法 --> alt+shift+s+s
		 * 直接輸出一個對象的名稱,其實就是調用該對象的toString()方法
		 * 
		 * */
		
		System.out.println(s.getClass().getName()+'@'+Integer.toHexString(s.hashCode()));
		//ustc.lichunchun.object.demo.Student@1db9742
		System.out.println("----------------------");
		
		System.out.println(s.toString());//Student [name=null, age=0]
		System.out.println("----------------------");
		
		System.out.println(s);//Student [name=null, age=0]
		
	}

}
package ustc.lichunchun.object.demo;
/*
 * equals()這個方法,默認情況下比較的是地址值,一般來說意義不大。
 * 
 * 源碼:
 * 		public boolean equals(Object obj) {
 * 			//this - s1
 * 			//obj - s2
 *       	return (this == obj);
 *   	}
 * 
 * 所以我們要重寫equals()方法。怎麼重寫呢?
 * 		一般都是用來比較對象的成員變量值是否相同。
 * 重寫的代碼優化:提高效率,提高程序的健壯性。
 * 最終版:其實還是自動生成的 --> alt+shift+s+h
 * 
 * ==:
 * 		基本類型:比較的就是值是否相同
 * 		引用類型:比較的就是地址值是否相同
 * equlas:
 * 		只能比較引用類型。默認情況下,比較的是地址值。
 * 		不過,我們可以根據情況自己重寫該方法。一般重寫都是自動生成的,比較對象的成員變量值是否相同。
 */
public class StudentDemo2 {
	public static void main(String[] args) {
		Student s1 = new Student("林青霞", 27);
		Student s2 = new Student("林青霞", 27);
		System.out.println(s1 == s2);//false
		Student s3 = s1;
		System.out.println(s1 == s3);//true
		System.out.println("------------------");

		System.out.println(s1.equals(s1));//true
		System.out.println(s1.equals(s2));//true 如果不復寫,返回false
		System.out.println(s1.equals(s3));//true
		System.out.println("------------------");

		Student s4 = new Student("風清揚", 30);
		System.out.println(s1.equals(s4));//false
	}
}
package ustc.lichunchun.object.demo;
/*
 * protected Object clone():創建並返回此對象的一個副本。子類重寫此方法。
 * 
 * Clonable:此類實現了Clonable接口,以指示Object.clone()方法可以合法地對該類實例進行按字段複製。
 * 		這個接口是標記接口,沒有任何方法,只是用來告訴我們實現該接口的類就可以實現對象的複製了。
 */
public class StudentDemo3 {

	public static void main(String[] args) throws CloneNotSupportedException {
		//創建學生對象
		Student s = new Student();
		s.setName("林青霞");
		s.setAge(27);
		
		//淺克隆學生對象:實現對象的克隆,包括成員變量的數據複製
		Object obj = s.clone();
		Student s2 = (Student)obj;
		System.out.println("------------------");
		
		System.out.println(s.getName()+"---"+s.getAge());//林青霞---27
		System.out.println(s2.getName()+"---"+s2.getAge());//林青霞---27
		
		//以前的做法:兩個引用指向同一個對象
		Student s3 = s;
		System.out.println(s3.getName()+"---"+s3.getAge());//林青霞---27
		System.out.println("------------------");
		
		//其實是有區別的
		s3.setName("風清揚");
		s3.setAge(30);
		System.out.println(s.getName()+"---"+s.getAge());//風清揚---30
		System.out.println(s2.getName()+"---"+s2.getAge());//林青霞---27
		System.out.println(s3.getName()+"---"+s3.getAge());//風清揚---30
		
	}

}
package ustc.lichunchun.object.demo;

public class StudentTest {
	public static void main(String[] args) {
		Student s1 = new Student();
		System.out.println(s1.hashCode());// 31168322
		Student s2 = new Student();
		System.out.println(s2.hashCode());// 17225372
		Student s3 = s1;
		System.out.println(s3.hashCode());// 31168322
		System.out.println("-----------");

		Student s = new Student();
		Class c = s.getClass();
		String str = c.getName();
		System.out.println(str);//ustc.lichunchun.object.demo.Student
		System.out.println(new Student().getClass().getName());//鏈式編程 ustc.lichunchun.object.demo.Student
		System.out.println("-----------");
	}
}
Scanner類

    這裏,我們主要闡述一下用於接收鍵盤錄入數據的java.util.Scanner類,以及它的hasNextXxx()、nextXxx()方法的使用。具體代碼如下:

package ustc.lichunchun.scanner.demo;

/*
 * Scanner:用於接受鍵盤錄入數據。
 * 
 * 前面的時候:
 * 		A:導包
 * 		B: 創建對象
 * 		C:調用方法
 * 
 * System類下有一個靜態的字段:
 * 		public static final InputStream in;-->標準輸入流,對應着鍵盤錄入。
 */

import java.util.Scanner;

public class ScannerDemo {
	public static void main(String[] args) {
		//創建對象
		Scanner sc = new Scanner(System.in);
		
		int x = sc.nextInt();
		
		System.out.println("x = " + x);
		
	}
}
package ustc.lichunchun.scanner.demo;

import java.util.Scanner;

/*
 * 基本格式:
 * 		public boolean hasNextXxx(): 判斷是否是某種類型的元素
 * 		public Xxx nextXxx(): 獲取該元素
 * 
 * 舉例:用int類型的方法舉例
 * 		public boolean hasNextInt()
 * 		public int nextInt()
 * 
 * 注意:
 * 		InputMismatchException:輸入的和你想要的不匹配
 */

public class ScannerDemo2 {
	public static void main(String[] args) {
		//創建對象
		Scanner sc = new Scanner(System.in);
		
		//獲取數據
		if(sc.hasNextInt()){
			int x = sc.nextInt();
			System.out.println("x: "+x);
		}else{
			System.out.println("您輸入的數據有誤");
		}
	}
}
package ustc.lichunchun.scanner.demo;

import java.util.Scanner;

/*
 * 常用的兩個方法:
 * 		public int nextInt():獲取一個int類型的值
 * 		public String nextLine():獲取一個String類型的值
 * 
 * 出現問題了:
 * 		先獲取一個數值,在獲取一個字符串,會出現一個問題。
 *		主要原因:就是那個換行符號的問題。 
 * 如何解決呢?
 * 		A:先獲取一個數值後,在創建一個新的鍵盤錄入對象獲取字符串。
 * 		B:把所有的數據都先按照字符串獲取,然後要什麼,你就對應的轉換爲什麼。
 */

public class ScannerDemo3 {
	public static void main(String[] args) {
		// 創建對象
		Scanner sc = new Scanner(System.in);

		// 獲取兩個int類型的值
		// int a = sc.nextInt();
		// int b = sc.nextInt();
		// System.out.println("a: " + a + ", b: " + b);
		// System.out.println("-----------------------");

		// 獲取兩個String類型的值
		// String s1 = sc.nextLine();
		// String s2 = sc.nextLine();
		// System.out.println("s1: " + s1 + ", s2: " + s2);

		// 先獲取一個字符串,在獲取一個int值
		// String s1 = sc.nextLine();
		// int b = sc.nextInt();
		// System.out.println("s1: " + s1 + ", b: " + b);

		// 先獲取一個int值,在獲取一個字符串
//		int a = sc.nextInt();
//		String s2 = sc.nextLine();
//		System.out.println("a: " + a + ", s2: " + s2);
		// System.out.println("-----------------------");
		
		//解決一:
//		int a = sc.nextInt();
//		Scanner sc2 = new Scanner(System.in);
//		String s = sc2.nextLine();
//		System.out.println("a: " + a + ", s: " + s);
		
		//解決二:
		String s1 = sc.nextLine();
		int a = Integer.parseInt(s1);
		String s2 = sc.nextLine();
		System.out.println("a: " + a + ", s2: " + s2);
	}
}
String類

    接下來講述本篇的重點之一,java.lang.String字符串類的基本方法使用,以及一些實際的需求案例。首先闡述一下String類複寫Object類的equals()方法。

package ustc.lichunchun.string.demo;

public class StringDemo {

	public static void main(String[] args) {
		/*
		 * String演示
		 *  "abcd" --> 常量,一旦初始化就不會被改變。
		 */
		String str = "abcd";
//		str = "hello";
		String str1 = new String("abcd");

		System.out.println(str == str1);//false 比較的是地址值
		System.out.println(str1.equals(str));//true 字符串的equals覆蓋了Object類,比較的是字符串的內容是否相同
	
		//問,str和str1的區別?
		/*
		 * str在內存中只有一個對象。--> "abcd" 方法區的常量池中
		 * str1,在內存中有兩個對象。--> 方法區的常量池中 以及 堆內存中通過構造函數創建的一個對象
		 */
		
		System.out.println("----------------------");
		
		String s1 = "abc";//-->在常量池中 爲 "abc" 分配了一片空間,地址值賦給s1,s1指向"abc"。
		String s2 = "abc";//-->創建"abc"臨時數據,到常量池裏去找,如果有,直接取地址賦給s2,如果沒有,存進常量池,在取地址給s2.
		
		System.out.println(s1 == s2);//true 常量池中只存一個"abc"
	}

}
package ustc.lichunchun.string.demo;

public class StringDemo2 {

	public static void main(String[] args) {
		/*
		 * "abcd"
		 * 
		 * 查閱API發現String類構造函數可以將字節數組,或者字符數組構造成字符串對象。
		 * 
		 * String類成員方法 API查找方式:確定返回值和參數列表的類型,以及函數名提供的信息。
		 * 
		 * 1.長度:int length()
		 * 
		 * 2.獲取指定位置字符:char charAt(int index)
		 * 
		 * 3.獲取字符所處的位置:int indexOf(int ch, int fromIndex)
		 */

		String str = "abcda";

		int len = str.length();

		char ch = str.charAt(0);// java.lang.StringIndexOutOfBoundsException
		
		int index = str.indexOf('a');//0
		
		int lastIndex = str.lastIndexOf('a');//4
		
		System.out.println(str.indexOf('c', 2));//2
	}
}
    首先,我們通過查閱API文檔,來查找一些基本的針對字符串String類型數據的操作,比如返回字符串中字符個數、字符串特定位置字符、首次出現某字符的位置等,然後,舉一個字符串數組排序的例子,我們選用的是選擇排序,注意其中比較兩個字符串大小,使用的是compareTo()方法。

package ustc.lichunchun.string.test;

import java.util.Arrays;

public class StringTest {

	public static void main(String[] args) {

		/*
		 * 不是魚,是漁!查閱API文檔。
		 * 
		 * 1.字符個數。 
		 * 		int length()
		 * 
		 * 2.把字符串分解很多字符 
		 * 		char[] toCharArray()
		 * 
		 * 3.對字符串中的字符排序。字符串中沒有該方法。自定義。
		 * 		 String sort(String str)
		 * 
		 * 4.通過字符串中指定位置獲取對應的字符。 
		 * 		char charAt(int index)
		 * 
		 * 5.通過字符串中指定字符獲取其第一次出現的位置。
		 * 		 int indexOf(int ch)
		 * 
		 * 6.指定的字符串在原字符串中是否出現以及出現的位置。
		 * 		 int indexOf(String str)
		 * 
		 * 7.字符串是否以指定的字符串開頭、結尾,是否包含指定字符串。
		 * 		 boolean startsWith(String prefix)
		 *		 boolean endsWith(String suffix)
		 *		 boolean contains(String s)
		 * 
		 * 8.獲取字符串中的一部分--子串。 
		 * 		String sunstring(int beginIndex, int endIndex) --> beginIndex~endIndex-1
		 * 
		 * 9.將字符串中的指定字符修改爲另一個字符。"abc" "kbc" 
		 * 		String replace(char oldChar, char newChar)
		 * 
		 * 10.去除字符串兩端的空白,"  ab c  " "ab c" 
		 * 		String trim()
		 * 
		 * 11.字符串可以比較大小嗎?如果有!,將字符串數組排序。 
		 * 		int compareTo(String anotherString)
		 * 
		 * 記住: 基本類型數值可以通過比較運算符比較大小和相等。 > < == 
		 * 對象也可以比較是否相等,誰大誰小。都是通過方法完成。
		 * 對象比較相同:Object類中的boolean equals(Object obj):子類一般情況下都會複寫,建立自己判斷相同的依據。
		 * 對象比較大小用的也是方法:compareTo() 
		 * 該功能有三種情況。所以使用int類型。正數 負數 零. 
		 * 前者大於後者返回正數,前者小於後者返回負數,前者等於後者返回零。
		 * 
		 * 繼承父類,繼承的是基本方法,比如Object類中的比較相同的equals()方法。
		 * 子類特有的方法,比如String類比較大小的方法,父類Object沒有。
		 * 那麼,compareTo()方法從哪裏而來?-->Comparable接口!
		 * 所以,所有的類具備的比較性都是來自於Comparable接口的compareTo()方法。
		 * 故Person類想要比較大小,就得實現Comparable接口!
		 */

		// 對字符串中的字符排序
		String str = "qwertyuiop";
		System.out.println(sort(str));// eiopqrtuwy
		System.out.println("---------------------------");

		// 兩個字符串比較大小
		int num = "abc".compareTo("xyz");
		System.out.println(num);// -23
		System.out.println("---------------------------");

		String[] strs = { "nba", "abc", "cba", "haha","qq", "hiahia" };
		printArray(strs);
		// 對字符串數組排序
		sort(strs);
		printArray(strs);

	}

	/**
	 * 對字符串中的字符排序(Arrays工具)
	 */
	public static String sort(String str) {
		char[] c = str.toCharArray();
		Arrays.sort(c);
		return new String(c);
	}

	/**
	 * 對字符串數組排序 (選擇排序)
	 */
	public static void sort(String[] strs) {
		for (int x = 0; x < strs.length - 1; x++) {
			for (int y = x + 1; y < strs.length; y++) {
				if (strs[x].compareTo(strs[y]) > 0) {
					swap(strs, x, y);
				}
			}
		}
	}
	/**
	 * 交換字符串數組中的兩個字符串 
	 */
	private static void swap(String[] strs, int x, int y) {
		String temp = strs[x];
		strs[x] = strs[y];
		strs[y] = temp;
	}

	/**
	 * 打印字符串數組
	 */
	public static void printArray(String[] strs) {
		for (int i = 0; i < strs.length; i++) {
			if (i != strs.length - 1)
				System.out.print(strs[i] + ", ");
			else
				System.out.println(strs[i]);
		}
	}

}
    實例2,String類的replase()方法返回的是一個新的字符串,這點注意。並且,字符串是常量,一旦被初始化,就不會被改變!
package ustc.lichunchun.string.test;

public class StringTest3 {

	public static void main(String[] args) {
		
		String s1 = "hello";
		String s2 = "java";//字符串是常量,一旦初始化,就不會被改變!
		
		test(s1,s2);
		
		System.out.println(s1+"..."+s2);//hello...java
	}
	public static void test(String s1, String s2){
		s2.replace('a', 'o');//返回一個新的字符串。替換完後,內存中有三個字符串: hello、java、jovo。s2還是指向java。
		s1 = s2;
		System.out.println(s1+"----"+s2);
	}
}
    實例3,統計子串在整串中出現的次數。如"nbadfnbaghjnbaklnba"中"nba"出現的次數。主要使用了String類的indexOf()方法。

package ustc.lichunchun.string.test;

public class StringTest4 {

	public static void main(String[] args) {
		/*
		 * 需求:子串在整串中出現的次數。"nbadfnbaghjnbaklnba"
		 * 
		 * 思路:
		 * 1.需要計數
		 * 2.找到一個nba就計數。
		 * 3.咋找?那就是字符串中查找字符串,字符串中怎麼找應該字符串自己很清楚。
		 * 所以找String類。
		 * 4.如果有這個方法,每找一次需要計數,需要找n次。循環完成。
		 * 
		 * 步驟:
		 * 1.定義變量,用於計數。
		 * 2.需要循環,循環條件是,找到了就繼續循環,沒有找到就停。
		 * int indexOf(String)
		 * 3.循環內對計數器自增。
		 */
		
		String str = "nbadfnbaghnbajnbaklnba";
		String key = "nba";
		
		int count = getKeyCount(str, key);
		System.out.println("count = "+count);
	}

	public static int getKeyCount(String str, String key) {
		
		//定義變量計數。
		int count = 0;
		//定義變量,記錄每次找到的角標。
		int index = 0;
		//循環。條件是indexOf查找的方法返回的結果不是-1。而且要明確下次查找的位置,所以使用indexOf(String, fromIndex)。
		while((index = str.indexOf(key, index)) != -1){
			count++;
			//每找完一次,都要確定下次要找的起始位置。上次位置+key的長度。
			index += key.length();
		}
		return count;
	}
}
    實例4,找出兩個字符串的最大相同子串。主要使用了for嵌套循環和String類的contains()方法。

package ustc.lichunchun.string.test;

public class StringTest5 {

	public static void main(String[] args) {
		/*
		 * 需求:兩個字符串的最大相同子串。
		 * "sadfcctvghjkl"
		 * "zxcctvcv"
		 * 
		 * 分析:
		 * 0--length								zxcctvcv
		 * 0--length-1  1--length					zxcctvc		xcctvcv
		 * 0--length-2  1--length-1  2--length		zxcctv		xcctvc		cctvcv
		 * ...
		 * 可以使用for嵌套循環!
		 */
		
		String str1 = "sadfcctvghjkl";
		String str2 = "zxcctvcv";
		
		String subMax = getMaxSub(str1, str2);
		System.out.println("MaxSubString:"+subMax);
	}

	public static String getMaxSub(String str1, String str2) {

		//首先判斷誰是長串,誰是短串。
		String longStr, shortStr;
		longStr = str1.length()>str2.length()?str1:str2;
		shortStr = str1.equals(longStr)?str2:str1;
		System.out.println("long: "+longStr);
		System.out.println("short: "+shortStr);
		
		for(int x = 0; x < shortStr.length(); x++){
			for(int y = 0, z = shortStr.length()-x; z <= shortStr.length(); y++,z++){
				String temp = shortStr.substring(y, z);
				if (longStr.contains(temp))
					return temp;
			}
		}
		return null;
	}
}
    實例5,對字符串中字符進行自然順序排序。主要使用了String類的toCharArray()方法、String類的字符數組構造函數,以及java.util.Arrays類中的sort()靜態方法。
package ustc.lichunchun.string.test;

import java.util.Arrays;

public class StringTest6 {

	public static void main(String[] args) {
		/*
		 * 需求:對字符串中字符進行自然順序排序。
		 */
		String str = "zcxdvbnam";
		System.out.println(str);
		String sortString = sortChar(str);
		System.out.println(sortString);
	}

	public static String sortChar(String str) {
		char[] chs = stringToArray(str);
		sort(chs);
		return toString(chs);
	}

	private static String toString(char[] chs) {
		return new String(chs);
	}

	private static void sort(char[] chs) {
		Arrays.sort(chs);
	}

	private static char[] stringToArray(String str) {
		return str.toCharArray();
	}
}
    實例6,模擬一個trim()功能一致的方法。去除字符串兩端的空白。其實只要定義兩個變量,一個從頭開始,一個從尾開始遍歷字符串即可,注意角標越界情況的避免。主要使用了String類的subString()方法。

package ustc.lichunchun.string.test;

public class StringTest7 {

	public static void main(String[] args) {
		
		/*
		 * 需求:模擬一個trim功能一致的方法。去除字符串兩端的空白。
		 * 
		 * 思路:
		 * 1.定義兩個變量。
		 * 一個作爲從頭開始判斷字符串空格的角標。不斷++。
		 * 一個座位從尾開始判斷字符串空格的角標。不斷--。
		 * 2.判斷到不是空格爲止,取頭尾之間的字符串即可。
		 */
		
		String s = "    ab  c     ";
		
		s = myTrim(s);
		System.out.println("-"+s+"-");
		
	}

	public static String myTrim(String s) {
		int start = 0, end = s.length()-1;
		while(start <= end && s.charAt(start) == ' ')//start <= end --> 預防"  "的情況,角標越界!
			start++;
		while(start <= end && s.charAt(end) == ' ')
			end--;
		return s.substring(start, end+1);
	}
}
    實例7,模擬用戶登錄,給3次機會。這裏主要需要考慮每次循環輸出提示結果的不同情況,建議使用for循環。使用的是Scanner和String類。

package ustc.lichunchun.string.test;

import java.util.Scanner;
/*
 * 模擬登陸,給三次機會,並提示還有幾次。
 * 
 * 分析:
 * 		A:定義用戶名和密碼。目前假設是已存在的。
 * 		B: 鍵盤錄入用戶名和密碼。
 * 		C: 比較用戶名和密碼。
 * 				如果都相同,則登陸成功
 * 				如果有一個不同,則登錄失敗
 * 		D:給三次機會,用循環改進,最好用for循環。
 */
public class StringTest8 {

	public static void main(String[] args) {
		// 定義用戶名和密碼。已存在的。
		String username = "932628234";
		String password = "ke20061019";

		// 給三次機會,用循環改進,最好用for循環。
		for (int x = 0; x < 3; x++) {
			// 0,1,2
			// 鍵盤錄入用戶名和密碼。
			Scanner sc = new Scanner(System.in);
			System.out.print("請輸入QQ用戶名:");
			String name = sc.nextLine();
			System.out.print("請輸入QQ密碼:");
			String pwd = sc.nextLine();

			// 比較用戶名和密碼。
			if (name.equals(username) && pwd.equals(password)) {
				// 如果都相同,則登陸成功
				System.out.println("登陸成功!!!即將進入QQ...");
				break;
			} else {
				// 如果有一個不同,則登錄失敗
				// 2,1,0
				// 如果還有0次機會,應該換一種提示
				if ((2 - x) == 0)
					System.out.println("賬號被鎖定,請與管理員聯繫!");
				else
					System.out.println("登錄失敗,你還有" + (2 - x) + "次機會...");
			}
		}
	}
}
    實例8,模擬用戶登錄加強版,用戶在登錄成功的情況下,可以玩猜數字的小遊戲。數字的產生使用的是java.lang.Math類的random()方法。

package ustc.lichunchun.string.test;

import java.util.Scanner;
/*
 * 模擬登陸,給三次機會,並提示還有幾次機會。如果登陸成功,就可以玩猜數字小遊戲了。
 */
public class StringTest9 {
	public static void main(String[] args) {
		String username = "932628234";
		String password = "ke20061019";
		
		for(int x = 0; x < 3; x++){
			Scanner sc = new Scanner(System.in);
			System.out.print("請輸入QQ賬號:");
			String name = sc.nextLine();
			System.out.print("請輸入QQ密碼:");
			String pwd = sc.nextLine();
			
			if(name.equals(username) && pwd.equals(password)){
				System.out.println("登陸成功,開始玩遊戲");
				GuessNumberGame.start();
				break;
			}else{
				if((2-x) == 0)
					System.out.println("賬號被鎖定,請與管理員聯繫!");
				else
					System.out.println("登錄失敗,你還有"+(2-x)+"次機會...");
			}
		}
	}
}
package ustc.lichunchun.string.test;

import java.util.Scanner;

public class GuessNumberGame {
	private GuessNumberGame() {
	}

	public static void start() {
		//產生一個隨機數
		int number = (int) (Math.random() * 100) + 1;
		while (true) {
			//鍵盤錄入數據
			Scanner sc = new Scanner(System.in);
			System.out.print("請輸入你猜的數字(1-100):");
			int guessNumber = sc.nextInt();
			
			//判斷
			if (guessNumber > number) {
				System.out.println("你猜的數字" + guessNumber + "大了");
			} else if (guessNumber < number) {
				System.out.println("你猜的數字" + guessNumber + "小了");
			} else {
				System.out.println("恭喜你,猜中了!!!");
				break;
			}
		}
	}
}
    加入猜數字遊戲的用戶登錄模擬程序,運行結果如下示例 (這裏的qq密碼不是真的喲,可別想盜我號。。敲打):


StringBuffer類

    java.lang.StringBuffer類是字符串緩衝區,可以理解爲一個長度可以變化、允許對其中元素進行”增刪改查“的字符容器,實際上是一個可變長度的數組,超出內部數組長度後,新建數組長度要是原數組的1.5或者1.75等倍數。它主要有append()insert()插入方法。注意append()方法在緩衝區中增加了新的字符串以後,返回的仍然是當前StringBuffer對象的引用,這在下面實際的例子中有舉出。

package ustc.lichunchun.stringbuffer.demo;

public class StringBufferDemo {

	public static void main(String[] args) {
		/*
		 * StringBuffer:字符串緩衝區。
		 * 作爲一個字符容器。
		 * 特點:
		 * 1.長度可以變化。
		 * 2.可以對內容通過指定方法進行修改。
		 * 3.容器對象一般都會具備對容器中的元素進行操作的功能,如增刪改查。
		 * 4.緩衝區可以存儲不同類型的數據。
		 * 5.最終緩衝區存儲完的數據都會變成字符串。(字符串緩衝區只起着臨時存儲的作用)
		 */
		String str = "a"+4+'c';
		//在內存中的過程.
		//1.創建一個字符串緩衝區容器。2.將要組成字符串的元素先存儲起來。3.最後將緩衝區填充數據變成字符串。
		str = new StringBuffer().append("a").append(4).append('c').toString();
		
		System.out.println(str);
	}
}
package ustc.lichunchun.stringbuffer.demo;

public class StringBufferDemo2 {

	public static void main(String[] args) {
		
		/*
		 * StringBuffer
		 * 緩衝區可以對數據進行臨時存儲。
		 * 
		 * 瞭解緩衝區的常見方法。
		 * 添加元素:
		 * StringBuffer append(各種類型的數據) --> 追加
		 * StringBuffer insert(index, 各種類型的數據) --> 指定位置添加
		 */
		
		//1.創建一個緩衝區對象
		StringBuffer sb = new StringBuffer();
		
		//2.追加一個字符串
		sb.append("abc");
		
		//3.插入一個boolean值true
		sb.insert(1, true);
		
		//4.刪除字符
//		sb.delete(1, 4);
		
		//5.修改字符
		sb.replace(1, 5, "false");//atruebc-->afalsebc 先將子字符串中的字符移除,然後將指定的 String 插入 start
		
//		sb.setLength(20);
		
		sb.reverse();//cbeslafa
		
		System.out.println(sb);//println方法會將所有要打印的數據先轉成字符串在輸出。對於對象會自動調用toString方法。
		
		/*
		 * StringBuffer字符串緩衝區維護了一個"可變長度的數組"
		 * 解釋:其實就是超出內部數組長度後,新建數組長度要是原數組的1.5或者1.75等倍數。
		 * 並將原數組的數據複製到新數組中,並將新的元素也添加到新數組中。
		 */
	}
}
    我們來舉兩個實際使用例子:

package ustc.lichunchun.stringbuffer.demo;

public class StringBufferTest {

	public static void main(String[] args) {
		/*
		 * 1.通過緩衝區,將要打印的矩形組成元素*進行存儲後,一次性返回,並輸出。
		 * 
		 * 2.將int數組的元素轉成字符串。格式爲:[34, 12,67]
		 * 
		 * 什麼時候用字符串緩衝區?
		 * 數據很多,個數無所謂確定,類型無所謂確定,只要最後都轉成字符串,就使用StringBuffer這個容器。
		 * 
		 * 使用侷限性:
		 * 1.必須最終轉成字符串。
		 * 2.無法對存儲進來的元素進行單獨操作。因爲存儲進來的元素都變成了字符串。
		 * {"abc","haha"} StringBuffer sb = new StringBuffer("abc");sb.append("haha");--->"abchaha"
		 */

		StringBuffer buf1 = new StringBuffer("hello");
		StringBuffer buf2 = new StringBuffer("java");
		test(buf1, buf2);
		System.out.println(buf1 + "...." + buf2);// hellojava....java

		String rec = draw(5, 6);
		System.out.print(rec);

		int[] arr = {34,12,67,43,29};
		String s = toString2(arr);
		System.out.println(s);
	}

	public static void test(StringBuffer buf1, StringBuffer buf2) {
		buf1.append(buf2);// 在當前對象後追加buf2字符串,返回的仍然是buf1對象的一個引用。
		buf1 = buf2;
	}

	/**
	 * 畫矩形的功能。 將需要組成矩形的元素進行臨時存儲。
	 */
	public static String draw(int row, int col) {
		// 定義一個臨時容器。
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				sb.append("*");
			}
			sb.append("\n");
		}
		return sb.toString();
	}
	
	/**
	 * int數組轉成字符串,通過StringBuffer。 --> 直接放到緩衝區中進行數組的存儲。--> 較好!
	 */
	public static String toString2(int[] arr){
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < arr.length; i++) {
			if (i!=arr.length-1)
				sb.append(arr[i]+", ");
			else
				sb.append(arr[i]+"]");
		}
		return sb.toString();
	}
	
	/**
	 * int數組轉成字符串。--> 之前的做法是不斷地延長字符串,不斷地在常量池中產生常量。
	 */
	public static String toString(int[] arr) {
		String str = "[";
		for (int i = 0; i < arr.length; i++) {
			if(i != arr.length-1)
				str+=arr[i]+", ";
			else
				str+=arr[i]+"]";
		}
		return str;
	}
}
StringBuilder類

    JDK1.5之後,又出現了StringBuilder類。它與StringBuffer類的區別在於:

    StringBuffer類是線程同步的,StringBuilder類是線程不同步的。

package ustc.lichunchun.stringbuilder;

public class StringBuilderDemo {

	public static void main(String[] args) {
		/*
		 * JDK1.5以後,出現了StringBuilder和StringBuffer用法一樣。
		 * StringBuffer是線程同步的。
		 * StringBuilder是線程不同步的。
		 * 一把可以建議選擇SringBuilder。因爲速度快。
		 * 
		 * synchronized append();
		 * 
		 * synchronized insert();
		 * 
		 * synchronized delete();
		 */
	}
	/*class MyStringBuffer{
		StringBuilder sb = new StringBuilder();
		public synchronized void append(obj){
			sb.append(obj);
		}
	}*/
}
基本數據類型對象包裝類

    依據面向對象的思想,java也將基本數據值封裝成了對象。這樣可以在對象中定義更多的屬性和行爲對基本數據進行操作。基本數據類型對象包裝類的重要功能:在基本類型和String類型之間互相轉換。我們這裏主要舉例Integer類,以及它的parseInt()valueOf()intValue()toString()等方法。

package ustc.lichunchun.wrapper.demo;

public class WrapperDemo {

	public static void main(String[] args) {
		/*
		 * 基本數據類型對象包裝類。
		 * 將基本數據值封裝成了對象。
		 * 好處:可以在對象中定義更多的屬性和行爲對基本數據進行操作。
		 * 
		 * 八種基本數據類型都有對應的對象包裝類和相應的描述。
		 * byte		Byte
		 * short	Short
		 * int		Integer
		 * long		Long
		 * boolean	Boolean
		 * float	Float
		 * double	Double
		 * char		Character
		 * 
		 * 基本數據類型對象包裝類的重要功能:在基本類型和String類型之間互相轉換。
		 */
		
		//int的範圍最值,只有int最清楚。所以找int對應的對象最合適。
		System.out.println(Integer.MAX_VALUE);
		System.out.println(Integer.toBinaryString(8));//可以將十進制整數轉成其他進制字符串
		System.out.println(Integer.toString(6));
		System.out.println("-----------------");
		
		/*
		 * 字符串轉成基本數據類型
		 * 使用的是 parse基本類型(字符串):parseInt parseByte parseDouble parseBoolean
		 */
		System.out.println("23"+4);
		System.out.println(Integer.parseInt("23")+4);
		System.out.println(Integer.parseInt("110", 2));//可以將其他進制的字符串轉成十進制整數
		System.out.println("-----------------");
		
		/*
		 * 基本數據類型轉成字符串
		 */
		System.out.println(""+3+4);
		System.out.println(Integer.toString(3)+8);
		
		/*
		 * 爲了對整數進行更多的操作,可以將整數封裝成對象。
		 * 通過Integer的方法完成。
		 * int --> Integer
		 */
		Integer i1 = new Integer(4);//構造方法
		Integer i11 = new Integer("4");//構造方法
		
		Integer i2 = Integer.valueOf(4);//靜態方法
		
		/*
		 * Integer --> int
		 */
		Integer x1 = new Integer(4);
		int n1 = x1.intValue();
	}
}

    這裏我們舉一個例子,對字符串中的數值進行升序排序後,生成一個數值有序的字符串,比如:"23 10 -8 0 3 7 108"變成"-8 0 3 7 10 23 108"。注意解題的思想,將任務分塊,自頂向下解決問題。主要用到了String類的split()方法、Integer的parseInt()方法、Arrays的sort()方法、StringBuilder的append()toString()方法。

package ustc.lichunchun.wrapper.demo;

import java.util.Arrays;

public class Test {

	private static final String SEPARATER = " ";
	
	public static void main(String[] args) {
		/*
		 * "23 10 -8 0 3 7 108"對字符串中的數值進行升序排序後,生成一個數值有序的字符串。
		 * "-8 0 3 7 10 23 108"
		 *  思路:
		 *  1.排序,而且是對整數數值排序。
		 *  2.排序的元素都在字符串中。如何取出?
		 *  3.找String類的功能。而且發現,數字之間的間隔都是相同的空格,有規律。如果有這個功能,結果是多個字符串。String[] split(String)
		 *  4.將獲取到的數字格式的字符串轉成具體的數字並存儲到數組中。
		 *  5.對數組排序。
		 *  6.將數組轉成字符串。
		 */

		String numStr = "23 10 -8 0 3 7 108";
		String sortStr = sortNumberString(numStr);
		System.out.println(numStr);
		System.out.println(sortStr);

	}
	/**
	 * 對一個有多個數值的字符串,進行數值的排序。
	 * @param numStr
	 * @return
	 */
	public static String sortNumberString(String numStr) {
		//1.將給定的字符串分解成多個數字格式字符串。
		String[] numStrs = toStringArray(numStr);
		
		//2.將字符串數組轉成int數組。
		int[] nums = toIntArray(numStrs);
		
		//3.對數組排序。
		sort(nums);
		
		//4.將int數組轉成字符串 並返回。
		return toString(nums);
		
	}
	
	/**
	 * 將int數組轉成字符串
	 */
	private static String toString(int[] nums) {
		//1.定義一個字符串緩衝區。
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nums.length; i++) {
			if(i != nums.length-1)
				sb.append(nums[i]+SEPARATER);
			else
				sb.append(nums[i]);
		}
		return sb.toString();
	}
	/**
	 * 對int數組進行升序排序。
	 */
	private static void sort(int[] nums) {
		Arrays.sort(nums);
	}
	/**
	 * 將字符串數組轉成int類型的數組 
	 */
	private static int[] toIntArray(String[] numStrs) {
		//1.創建一個int類型數組,長度和字符串數組的長度一致。
		int[] nums = new int[numStrs.length];
		//2.對字符串數組進行遍歷。
		for (int i = 0; i < numStrs.length; i++) {
			//3.將字符串數組中的元素通過parseInt轉換後,賦值給int類型數組。
			nums[i] = Integer.parseInt(numStrs[i]);
		}
		return nums;
	}
	/**
	 * 將字符串按照指定的分隔,轉成字符串數組。 
	 */
	private static String[] toStringArray(String numStr) {
		//使用字符串的split(regax)
		return numStr.split(" ");
	}

}

自動裝箱拆箱

    這是JDK1.5以後有的技術,意圖可以解釋爲希望像操作int一樣的操作Integer。

package ustc.lichunchun.wrapper.demo;

public class WrapperDemo2 {

	public static void main(String[] args) {
		/*
		 * JDK1.5以後,新的技術:自動裝箱自動拆箱。
		 * 希望像操作int一樣的操作Integer。
		 */
        //Integer i = new Integer(4);
		//JDK1.5
		Integer i = 4;//自動裝箱。Integer.valueOf(4); --> new Integer(4);
		
		i = i + 6;//右邊i的自動拆箱。i.intValue()+6	運算完的結果又一次裝箱賦值給i,也即左邊的i又指向了左邊裝箱後的Integer對象。
		
		Integer x = new Integer(100);
		Integer y = new Integer(100);
		System.out.println(x == y);//false	比較的是對象地址值
		System.out.println(x.equals(y));//true  Integer類複寫了Object的equals方法,比較的是int數值大小。
		System.out.println("---------------------------------");
		//jdk1.5以後,自動裝箱的值如果在byte範圍之內(-128 ~ 127),相同的值不會單獨開闢空間,而是重複利用。
		Integer m = 127;//200 100 129
		Integer n = 127;//200
		System.out.println(m == n);//true (false)
		System.out.println(m.equals(n));//true
		System.out.println("---------------------------------");
		
		sop("i="+i);
		sop(5);
	}
	public static void sop(Object s){//Object s = Integer.valueOf(5);
		System.out.println(s);
	}
}
    好了,這部分關於eclipse使用、字符串處理問題的討論就說到這裏,讀完這篇博客,你應該懂得了如何去查閱JDK的API文檔,從而使用java類提供好的一些成員方法來解決實際問題。後面我們來重點研究java中的集合框架

有任何問題請和我聯繫,共同進步:[email protected]

轉載請聲明出處:http://blog.csdn.net/zhongkelee/article/details/46694955

源碼下載 (內含eclipse快捷鍵和java API文檔)

發佈了50 篇原創文章 · 獲贊 137 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章