public class MultiplicationTable {
//九九乘法表
//v1.2
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
if (j % i == 0) {
System.out.print(j + " * " + i + " = " + (j * i) + "\n");
}
else
System.out.print(j + " * " + i + " = " + (j * i) + ",");
}
// System.out.println();
}
}
}
public class IsoscelesTriangle {
/**
* 等腰三角形
* @author cmz
* @date 2016/06/03
* @version 1.0
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入腰長:");
int num = input.nextInt();
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= num - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i - 1; j++) {
System.out.print("*");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
**
* 數組去重
*
* @author cmz
* @date 2016/06/03
* @version 1.0
*
*/
public class StringArrayAbandonRepeat {
public static void main(String[] args) {
String[] str = { "Java", "C++", "Php", "C#", "Python", "C++", "Java" };
// String [] str = {"13", "212", "13", "13", "13", "2", "1"};
// String [] str = {"11", "22", "22", "44", "44", "23", "13"};
// String [] str = {"111", "111", "22", "44", "44", "111", "111"};
String[] strNew = AbandonRepeat(str);
System.out.println("數組去重的結果:" + Arrays.toString(strNew));
}
/**
* @version v1.1
* @param str
* @return String[] dateTime 2016/05/30
*/
public static String[] AbandonRepeat(String[] str) {
int numOfNull = 0;
// 聲明sreNew的長度為傳人數組str的長度
String[] strNew = new String[str.length];
System.out.println("AbandonRepeat方法内->數組去重前->str = "
+ Arrays.toString(str));
// 兩重for循環中,如果有兩個元素相同,則把第一個元素置為空字元串,
// 特殊地,對于有超過2個以上相同的元素,也可以保留1個
for (int i = 0; i < str.length; i++) {
for (int j = i; j < str.length; j++) {
if (i == j) {
continue;
} else if (str[i].equals(str[j])) {
str[i] = "";
}
}
}
System.out.println("AbandonRepeat方法内->中間狀态->str = "
+ Arrays.toString(str));
// 忽略含有空字元串的元素,其他的元素指派給數組strNew
for (int k = 0, i = 0; i < str.length; i++) {
if (str[i].equals(new String(""))) {
// 計算有多少個空字元串,也用于計算strNew數組中有多少個null
numOfNull++;
continue;
} else {
strNew[k] = str[i];
k++;
}
}
System.out.println("AbandonRepeat方法内->去重後->strNew = "
+ Arrays.toString(strNew));
// 新數組strAbandonNull聲明的長度為原數組的長度減去null的個數
String[] strAbandonNull = new String[str.length - numOfNull];
for (int i = 0; i < strAbandonNull.length; i++) {
strAbandonNull[i] = strNew[i];
}
return strAbandonNull;
}
}
/**
* 數組去重,另一個版本
*
* @author cmz
* @date 2016/06/03
* @version 1.1
*
*/
public class StringArrayAbandonRepeat {
public static void main(String[] args) {
StringArrayAbandonRepeat saar = new StringArrayAbandonRepeat();
String[] str = { "Java", "C++", "Php", "C#", "Python", "C++", "Java" };
// String [] str = {"13", "212", "13", "13", "13", "2", "1"};
// String [] str = {"11", "22", "22", "44", "44", "23", "13"};
// String [] str = {"111", "111", "22", "44", "44", "111", "111"};
String[] strResult = saar.AbandonRepeat(str);
System.out.println("數組去重的結果:" + Arrays.toString(strResult));
}
/**
* @version v1.2
* @param str
* @dateTime 2016/06/03
*/
public String[] AbandonRepeat(String[] str) {
//用于數組中空字元串的計數
int numOfNull = 0;
System.out.println("AbandonRepeat方法内->數組去重前->str = "
+ Arrays.toString(str));
// 兩重for循環中,如果有兩個或者兩個以上的元素相同,則把除了第一個元素外的重複元素置為空字元串
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < i; j++) {
if (str[i].equals(str[j])) {
str[i] = "";
// 計算有多少個空字元串,用于計算strRemoveNull的長度
numOfNull++;
break;
}
}
}
System.out.println("AbandonRepeat方法内->中間狀态->str = "
+ Arrays.toString(str));
// 聲明數組strIncludeNull的長度 = 原數組str長度
String[] strIncludeNull = new String[str.length];
for (int i = 0, j = 0; i < strIncludeNull.length; i++) {
// 忽略含有空字元串的元素,其他的元素指派給數組strIncludeNull
if (!str[i].equals(new String(""))) {
strIncludeNull[j] = str[i];
j++;
}
}
// 數組strRemoveNull用于存儲strIncludeNull中除了null之外的元素
String[] strRemoveNull = new String[strIncludeNull.length - numOfNull];
for (int i = 0; i < strRemoveNull.length; i++) {
strRemoveNull[i] = strIncludeNull[i];
}
System.out.println("AbandonRepeat方法内->去重後->數組strRemoveNull = "
+ Arrays.toString(strRemoveNull));
return strRemoveNull;
}
}
第六次課的總結及思考
一、運算符
1、算術運算符:+ - * / % ++ --
注意:(1)a++表示在a之後才++,是以在以下代碼中:
int a = 10;
System.out.println("前a = " + a);
System.out.println("a++ = " + (a++));
System.out.println("後a = " + a);
結果:前a = 10
a++ = 10
後a = 11
(2)--a表示在a之前已經--:
int a = 10;
System.out.println("前a = " + a);
System.out.println("--a = " + (--a));
System.out.println("後a = " + a);
結果:前a = 10
--a = 9
後a = 9
2、關系運算符:> < == >= <= !=
3、指派運算符:+= -= *= /= %=
4、邏輯運算符:&& || !
5、位運算符:
(1)與(&):2個操作數中,對應的2個位都是1時,才傳回1,否則傳回0
(2)或(|):2個操作數中,對應的2個位隻要有1個是1,結果就是1
(3)非(~):翻轉包括符号位的每一位。如:
int a = -5;
System.out.println(a+"= " + Integer.toBinaryString(a));
System.out.println("~a = " + Integer.toBinaryString((~a)));
結果:
-5= 11111111111111111111111111111011
~a = 100
注意:負數在計算機中是以補碼形式表示的,非運算就在補碼的基礎上進行
(4)異或(^):2個操作數中,對應的2個位,如果不同,則結果為1;相同,結果為0。如:
int a = 13;
int b = 7;
System.out.println(a+" = "+Integer.toBinaryString(a));
System.out.println(b+" = "+Integer.toBinaryString(b));
System.out.println("a ^ b = "+Integer.toBinaryString((a^b)));
結果:
13 = 1101
7 = 111
a ^ b = 1010
int a = -13;
int b = 7;
System.out.println(a+" = "+Integer.toBinaryString(a));
System.out.println(b+" = "+Integer.toBinaryString(b));
System.out.println("a ^ b = "+Integer.toBinaryString((a^b)));
結果:
-13 = 11111111111111111111111111110011
7 = 111
a ^ b = 11111111111111111111111111110100
(5)左移(<< n):如ina a = 1; a = a << 1;即為a對應的二進制乘以2(左移,後面補0)
(6)右移(>>):如ina a = 1; a = a >> 1;即為a對應的二進制除以2(右移,前面補符号位)
(7)無符号位右移(>>>):忽略符号位,前面的最高位以0補齊
6、三目運算符:如:
int a = 9;
boolean result = a>0 ? true : false;
System.out.println(result);
三目運算符和if-else的運算效率的比較:對于大資料來說,if-else的運算效率比三目運算符快,比如下面的例子:找出0-1億内的偶數:
需要注意的是,可能會抛出java.lang.OutOfMemoryError: Java heap space異常,是以需要設定如下:
上圖中,-Xms表示java heap的初始化大小,預設為實體記憶體的1/64,-Xmx表示java heap的最大值,建議設定為實體記憶體的一半
具體的代碼如下:
//jvm占用的所有記憶體
long totalst=Runtime.getRuntime().totalMemory();
System.out.println("Totalst:"+totalst/(1024*1024)+"mb");
//jvm能夠從作業系統擷取的最大記憶體
long maxst=Runtime.getRuntime().maxMemory();
System.out.println("Max:"+maxst/(1024*1024)+"mb");
//jvm中空閑的記憶體
long freest=Runtime.getRuntime().freeMemory();
System.out.println("Free:"+freest/(1024*1024)+"mb");
System.out.println();
long startTime = System.currentTimeMillis();
List list = new ArrayList<>();
for (int i = 0; i < 100000000; i++) {
//把0——1000 0000zhong 的偶數找出來放到list
//三目運算符
list.add(i % 2 == 0 ? i : null);;
}
long endTime = System.currentTimeMillis();
long timeUsed = endTime - startTime;
System.out.println("三目運算符的耗時 :" + timeUsed + "ms");
long startTimes = System.currentTimeMillis();
List lists = new ArrayList<>();
for (int i = 0; i < 100000000; i++) {
//把0——1000 0000zhong 的偶數找出來放到list
//if-else
if(i % 2 ==0){
lists.add(i);
}
else {
lists.add(null);
}
}
long endTimes = System.currentTimeMillis();
long timeUseds = endTimes - startTimes;
System.out.println("if-else時 :" + timeUseds + "ms");
System.out.println();
//jvm占用的所有記憶體
long total=Runtime.getRuntime().totalMemory();
System.out.println("Total:"+total/(1024*1024)+"mb");
//jvm能夠從作業系統擷取的最大記憶體
long max=Runtime.getRuntime().maxMemory();
System.out.println("Max:"+max/(1024*1024)+"mb");
//jvm中空閑的記憶體
long free=Runtime.getRuntime().freeMemory();
System.out.println("Free:"+free/(1024*1024)+"mb");
結果:
Totalst:1917mb
Max:3555mb
Free:1907mb
三目運算符的耗時 :19382ms
if-else時 :2008ms
Total:3917mb
Max:3917mb
Free:1132mb
7、其他運算符:instanceof,用來在運作時指出對象是否為特定類(如Object)的一個執行個體
二、流程控制
1、while循環
2、do-while循環
3、for的一般形式和增強型for循環:增強型for循環可以用foreach快速輸入,它用于數組、集合周遊,不用聲明數組長度和疊代器
一般for循環和增強型for循環的比較:對于大資料的運算,增強型for循環比較快;對于小資料,二者的運作效率相差不大。如:
long startTime = System.currentTimeMillis();
String[] names = new String[50000000];
int j = 0;
for (String string : names) {
string = "xiaoming" + j;
j++;
}
long endTime = System.currentTimeMillis();
System.out.println("增強型for循環的耗時:" + (endTime - startTime));
long startTimes = System.currentTimeMillis();
String[] xm = new String[50000000];
for (int i = 0 ; i < xm.length;i++) {
xm[i] = "xingming" + i;
}
long endTimes = System.currentTimeMillis();
System.out.println("一般for循環的耗時:" + (endTimes - startTimes));
結果:
增強型for循環的耗時:3194
一般for循環的耗時:29892
4、break和continue、return
return:結束接下來的代碼,預設是return 0
三、數組
1、引用資料類型
數組中的每個元素的資料類型必須一緻,但有例外,如Fruit xx = {new Apple9(),new Peach()};這裡的Fruit是其他兩個類的父類-->(類是一種引用資料類型)
兩種數組的指派形式:
Fruit [] fruits = new Fruit[]{
new Apple(),
new Peach()
};
或:
Fruit [] fruits = {
new Apple(),
new Peach()
};
2、數組定義和初始化
(1)定義
建議用:type [] assayName;
還可以聲明如下:type arrayName [];
數組初始化之後才能使用,初始化就是為數組配置設定記憶體空間
(2)初始化
靜态初始化(已知每個值)
動态初始化 = new type[length];
3、通路數組元素
注意引發java.lang.ArrayIndexOutOfBoundsException異常的兩種典型原因:下标為Integer.MAX_VALUE和下标為-1
初始化記憶體不夠:
String [] names = new String[Integer.MAX_VALUE];
System.out.println("數組的最大長度:" + names.length);
抛出:Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
注意:引用資料類型的元素是引用,每個元素存儲的還是引用。指向另一塊記憶體
4、Arrays的方法介紹
(1)查找:binarySearch,如
int [] a = {12,121,223,11};
int b = Arrays.binarySearch(a, 12);
System.out.println(b);
結果:
(2)copyOf(int[] a.int ind length):複制制定數組,截取原數組的長度為length,如:
int [] a = {12,121,223,11};
int [] b = Arrays.copyOf(a, 1);
System.out.println(Arrays.toString(b));
結果:
[12]
(3)fill(int[] a, int fromIndex, int toIndex, int val)
:将指定的 int 值配置設定給指定 int類 型數組指定範圍(不包括toIndex對于的元素)中的每個元素。
預設值:int類型->0;boolean類型->false;引用資料類型->null
如:
int [] a = new int[5] ;
Arrays.fill(a, 1,4,1);
System.out.println(Arrays.toString(a));
結果:
[0, 1, 1, 1, 0]
(4) sort(int[] a):按升序排序,如
int [] a = {1,23,54,21};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
結果:
[1, 21, 23, 54]
(5)toString:以字元串形式傳回數組内容
四、檢視jvm資訊和代碼段的建立、導入、導出
1、檢視jvm占用的記憶體、能夠從作業系統擷取的最大記憶體、空閑的記憶體
//jvm占用的所有記憶體
long totalst=Runtime.getRuntime().totalMemory();
System.out.println("Totalst:"+totalst/(1024*1024)+"mb");
//jvm能夠從作業系統擷取的最大記憶體
long maxst=Runtime.getRuntime().maxMemory();
System.out.println("Max:"+maxst/(1024*1024)+"mb");
//jvm中空閑的記憶體
long freest=Runtime.getRuntime().freeMemory();
System.out.println("Free:"+freest/(1024*1024)+"mb");
2、如何把上面的代碼設定成代碼塊,以便以後快速輸入
(1)我使用的是myeclipse,打開windows->preferences->
(2)
(3)輸入以下内容
(4)确認,接着(也可以導入或将已存在的代碼段導出):
(5)以後想用到這段代碼,就可以:
五、對作業的思考
我檢視了舍友的三個作業,其中,發現他的數組去重方法代碼比較少,也設計得比較有技巧、有效率,相比之下,我的數組去重的方法的操作過程的代碼還是顯得比較複雜,用了2個數組,可能對于大型數組,我的時間複雜度可能比較大,效率也會比較低。總之,通過比較、學習,進而總結不足,積累編寫代碼的經驗,以後寫代碼的時候思路會更加清晰一點,也會更有效率地設計代碼,進而讓它更有效率地運作吧!