第 11 章常用類
第 11 章常用類
11.7 Math 類
11.7.1 基本介紹
Math 類包含用于執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。
11.7.2 方法一覽(均為靜態方法)
| 方法聲明 | 功能說明 |
|---|---|
static double abs(double a) |
返回 double 值的絕對值。 |
static float abs(float a) |
返回 float 值的絕對值。 |
static int abs(int a) |
返回 int 值的絕對值。 |
static long abs(long a) |
返回 long 值的絕對值。 |
static double acos(double a) |
返回一個值的反余弦;返回的角度范圍在 0.0 到 pi 之間。 |
static double asin(double a) |
返回一個值的反正弦;返回的角度范圍在 -pi/2 到 pi/2 之間。 |
static double atan(double a) |
返回一個值的反正切;返回的角度范圍在 -pi/2 到 pi/2 之間。 |
static double atan2(double y, double x) |
將矩形坐標 (x, y) 轉換成極坐標 (r, theta),返回所得角 theta。 |
static double cbrt(double a) |
返回 double 值的立方根。 |
static double ceil(double a) |
返回大于或等于參數的最小整數(double 類型)。 |
11.7.3 Math 類常見方法應用案例
public class MathMethod {
public static void main(String[] args) {
//看看Math常用的方法(靜態方法)
//1.abs 絕對值
int abs = Math.abs(-9);
System.out.println(abs);//9
//2.pow 求冪
double pow = Math.pow(2, 4);//2的4次方
System.out.println(pow);//16
//3.ceil 向上取整,返回>=該參數的最小整數(轉成double);
double ceil = Math.ceil(3.9);
System.out.println(ceil);//4.0
//4.floor 向下取整,返回<=該參數的最大整數(轉成double)
double floor = Math.floor(4.001);
System.out.println(floor);//4.0
//5.round 四舍五入 Math.floor(該參數+0.5)
long round = Math.round(5.51);
System.out.println(round);//6
//6.sqrt 求開方
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);//3.0
//7.random 求隨機數
// random 返回的是 0 <= x < 1 之間的一個隨機小數
// 思考:請寫出獲取 a-b之間的一個隨機整數,a,b均為整數 ,比如 a = 2, b=7
// 即返回一個數 x 2 <= x <= 7
// 解讀 Math.random() * (b-a) 返回的就是 0 <= 數 <= b-a
// (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
// (2) 使用具體的數給小伙伴介紹 a = 2 b = 7
// (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
// Math.random()*6 返回的是 0 <= x < 6 小數
// 2 + Math.random()*6 返回的就是 2<= x < 8 小數
// (int)(2 + Math.random()*6) = 2 <= x <= 7
// (3) 公式就是 (int)(a + Math.random() * (b-a +1) )
for(int i = 0; i < 100; i++) {
System.out.println((int)(2 + Math.random() * (7 - 2 + 1)));
}
//max , min 返回最大值和最小值
int min = Math.min(1, 9);
int max = Math.max(45, 90);
System.out.println("min=" + min);
System.out.println("max=" + max);
}
}
11.8 Arrays 類
11.8.1 Arrays 類常見方法應用案例
ArraysMethod01.java
Arrays 里面包含了一系列靜態方法,用于管理或操作數組(比如排序和搜索)
-
toString返回數組的字符串形式
Arrays.toString(arr) -
sort排序(自然排序和定制排序)
Integer arr[] = {1, -1, 7, 0, 89};
ArraysSortCustom.java -
binarySearch通過二分搜索法進行查找,要求必須排好序
int index = Arrays.binarySearch(arr, 3);
ArraysMethod02.java -
copyOf數組元素的復制
Integer[] newArr = Arrays.copyOf(arr, arr.length); -
fill數組元素的填充
Integer[] num = new Integer[]{9,3,2};
Arrays.fill(num, 99); -
equals比較兩個數組元素內容是否完全一致
boolean equals = Arrays.equals(arr, arr2); -
asList將一組值,轉換成list
List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
System.out.println("asList= " + asList);
public class ArraysMethod01 {
public static void main(String[] args) {
Integer[] integers = {1, 20, 90};
//遍歷數組
// for(int i = 0; i < integers.length; i++) {
// System.out.println(integers[i]);
// }
//直接使用Arrays.toString方法,顯示數組
// System.out.println(Arrays.toString(integers));//
//演示 sort方法的使用
Integer arr[] = {1, -1, 7, 0, 89};
//進行排序
//解讀
//1. 可以直接使用冒泡排序 , 也可以直接使用Arrays提供的sort方法排序
//2. 因為數組是引用類型,所以通過sort排序后,會直接影響到 實參 arr
//3. sort重載的,也可以通過傳入一個接口 Comparator 實現定制排序
//4. 調用 定制排序 時,傳入兩個參數 (1) 排序的數組 arr
// (2) 實現了Comparator接口的匿名內部類 , 要求實現 compare方法
//5. 先演示效果,再解釋
//6. 這里體現了接口編程的方式 , 看看源碼,就明白
// 源碼分析
//(1) Arrays.sort(arr, new Comparator()
//(2) 最終到 TimSort類的 private static <T> void binarySort(T[] a, int lo, int hi, int start,
// Comparator<? super T> c)()
//(3) 執行到 binarySort方法的代碼, 會根據動態綁定機制 c.compare()執行我們傳入的
// 匿名內部類的 compare ()
// while (left < right) {
// int mid = (left + right) >>> 1;
// if (c.compare(pivot, a[mid]) < 0)
// right = mid;
// else
// left = mid + 1;
// }
//(4) new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// Integer i1 = (Integer) o1;
// Integer i2 = (Integer) o2;
// return i2 - i1;
// }
// }
//(5) public int compare(Object o1, Object o2) 返回的值>0 還是 <0
// 會影響整個排序結果, 這就充分體現了 接口編程+動態綁定+匿名內部類的綜合使用
// 將來的底層框架和源碼的使用方式,會非常常見
//Arrays.sort(arr); // 默認排序方法
//定制排序
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Integer i1 = (Integer) o1;
Integer i2 = (Integer) o2;
return i2 - i1;
}
});
System.out.println("===排序后===");
System.out.println(Arrays.toString(arr));//
}
}
public class ArraysMethod02 {
public static void main(String[] args) {
Integer[] arr = {1, 2, 90, 123, 567};
// binarySearch 通過二分搜索法進行查找,要求必須排好
// 解讀
//1. 使用 binarySearch 二叉查找
//2. 要求該數組是有序的. 如果該數組是無序的,不能使用binarySearch
//3. 如果數組中不存在該元素,就返回 return -(low + 1); // key not found.
int index = Arrays.binarySearch(arr, 567);
System.out.println("index=" + index);
//copyOf 數組元素的復制
// 解讀
//1. 從 arr 數組中,拷貝 arr.length個元素到 newArr數組中
//2. 如果拷貝的長度 > arr.length 就在新數組的后面 增加 null
//3. 如果拷貝長度 < 0 就拋出異常NegativeArraySizeException
//4. 該方法的底層使用的是 System.arraycopy()
Integer[] newArr = Arrays.copyOf(arr, arr.length);
System.out.println("==拷貝執行完畢后==");
System.out.println(Arrays.toString(newArr));
//ill 數組元素的填充
Integer[] num = new Integer[]{9,3,2};
//解讀
//1. 使用 99 去填充 num數組,可以理解成是替換原理的元素
Arrays.fill(num, 99);
System.out.println("==num數組填充后==");
System.out.println(Arrays.toString(num));
//equals 比較兩個數組元素內容是否完全一致
Integer[] arr2 = {1, 2, 90, 123};
//解讀
//1. 如果arr 和 arr2 數組的元素一樣,則方法true;
//2. 如果不是完全一樣,就返回 false
boolean equals = Arrays.equals(arr, arr2);
System.out.println("equals=" + equals);
//asList 將一組值,轉換成list
//解讀
//1. asList方法,會將 (2,3,4,5,6,1)數據轉成一個List集合
//2. 返回的 asList 編譯類型 List(接口)
//3. asList 運行類型 java.util.Arrays#ArrayList, 是Arrays類的
// 靜態內部類 private static class ArrayList<E> extends AbstractList<E>
// implements RandomAccess, java.io.Serializable
List asList = Arrays.asList(2,3,4,5,6,1);
System.out.println("asList=" + asList);
System.out.println("asList的運行類型" + asList.getClass());
}
}
11.8.2 Arrays 類課堂練習
ArrayExercise.java
案例: 自定義Book類,里面包含name和price,按price排序(從大到小)。要求使用兩種方式排序,有一個 Book[] books = 4本書對象.
使用前面學習過的傳遞 實現Comparator接口匿名內部類,也稱為定制排序。,可以按照
(1)price從大到小 (2)price從小到大 (3) 書名長度從大到小
Book[] books = new Book[4];
books[0] = new Book("紅樓夢", 100);
books[1] = new Book("金梅新", 90);
books[2] = new Book("青年文摘20年", 5);
books[3] = new Book("java從入門到放棄~", 300);
public class ArrayExercise {
public static void main(String[] args) {
/*
案例:自定義Book類,里面包含name和price,按price排序(從大到小)。
要求使用兩種方式排序 , 有一個 Book[] books = 4本書對象.
使用前面學習過的傳遞 實現Comparator接口匿名內部類,也稱為定制排序。
可以按照 price (1)從大到小 (2)從小到大 (3) 按照書名長度從大到小
*/
Book[] books = new Book[4];
books[0] = new Book("紅樓夢", 100);
books[1] = new Book("金梅新", 90);
books[2] = new Book("青年文摘20年", 5);
books[3] = new Book("java從入門到放棄~", 300);
//(1)price從大到小
// Arrays.sort(books, new Comparator() {
// //這里是對Book數組排序,因此 o1 和 o2 就是Book對象
// @Override
// public int compare(Object o1, Object o2) {
// Book book1 = (Book) o1;
// Book book2 = (Book) o2;
// double priceVal = book2.getPrice() - book1.getPrice();
// //這里進行了一個轉換
// //如果發現返回結果和我們輸出的不一致,就修改一下返回的 1 和 -1
// if(priceVal > 0) {
// return 1;
// } else if(priceVal < 0) {
// return -1;
// } else {
// return 0;
// }
// }
// });
//(2)price從小到大
// Arrays.sort(books, new Comparator() {
// //這里是對Book數組排序,因此 o1 和 o2 就是Book對象
// @Override
// public int compare(Object o1, Object o2) {
// Book book1 = (Book) o1;
// Book book2 = (Book) o2;
// double priceVal = book2.getPrice() - book1.getPrice();
// //這里進行了一個轉換
// //如果發現返回結果和我們輸出的不一致,就修改一下返回的 1 和 -1
// if(priceVal > 0) {
// return -1;
// } else if(priceVal < 0) {
// return 1;
// } else {
// return 0;
// }
// }
// });
//(3)按照書名長度從大到小
Arrays.sort(books, new Comparator() {
//這里是對Book數組排序,因此 o1 和 o2 就是Book對象
@Override
public int compare(Object o1, Object o2) {
Book book1 = (Book) o1;
Book book2 = (Book) o2;
//要求按照書名的長度來進行排序
return book2.getName().length() - book1.getName().length();
}
});
System.out.println(Arrays.toString(books));
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
11.9 System 類
11.9.1 System 類常見方法和案例
exit退出當前程序arraycopy:復制數組元素,比較適合底層調用,一般使用Arrays.copyOf完成復制數組。int[] src={1,2,3}; int[] dest = new int[3]; System.arraycopy(src, 0, dest, 0, 3);currentTimeMillis:返回當前時間距離1970-1-1的毫秒數gc:運行垃圾回收機制System.gc();
public class System_ {
public static void main(String[] args) {
//exit 退出當前程序
// System.out.println("ok1");
// //解讀
// //1. exit(0) 表示程序退出
// //2. 0 表示一個狀態 , 正常的狀態
// System.exit(0);//
// System.out.println("ok2");
//arraycopy :復制數組元素,比較適合底層調用,
// 一般使用Arrays.copyOf完成復制數組
int[] src={1,2,3};
int[] dest = new int[3];// dest 當前是 {0,0,0}
//解讀
//1. 主要是搞清楚這五個參數的含義
//2.
// 源數組
// * @param src the source array.
// srcPos: 從源數組的哪個索引位置開始拷貝
// * @param srcPos starting position in the source array.
// dest : 目標數組,即把源數組的數據拷貝到哪個數組
// * @param dest the destination array.
// destPos: 把源數組的數據拷貝到 目標數組的哪個索引
// * @param destPos starting position in the destination data.
// length: 從源數組拷貝多少個數據到目標數組
// * @param length the number of array elements to be copied.
System.arraycopy(src, 0, dest, 0, src.length);
// int[] src={1,2,3};
System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]
//currentTimeMillens:返回當前時間距離1970-1-1 的毫秒數
// 解讀:
System.out.println(System.currentTimeMillis());
}
}
11.10 BigInteger 和 BigDecimal 類
11.10.1 BigInteger 和 BigDecimal 介紹
應用場景:
BigInteger適合保存比較大的整型BigDecimal適合保存精度更高的浮點型(小數)
11.10.2 BigInteger 和 BigDecimal 常見方法
BigInteger_java BigDecimal_java
add加subtract減multiply乘divide除
public class BigInteger_ {
public static void main(String[] args) {
//當我們編程中,需要處理很大的整數,long 不夠用
//可以使用BigInteger的類來搞定
// long l = 23788888899999999999999999999l;
// System.out.println("l=" + l);
BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
BigInteger bigInteger2 = new BigInteger("10099999999999999999999999999999999999999999999999999999999999999999999999999999999");
System.out.println(bigInteger);
//解讀
//1. 在對 BigInteger 進行加減乘除的時候,需要使用對應的方法,不能直接進行 + - * /
//2. 可以創建一個 要操作的 BigInteger 然后進行相應操作
BigInteger add = bigInteger.add(bigInteger2);
System.out.println(add);//
BigInteger subtract = bigInteger.subtract(bigInteger2);
System.out.println(subtract);//減
BigInteger multiply = bigInteger.multiply(bigInteger2);
System.out.println(multiply);//乘
BigInteger divide = bigInteger.divide(bigInteger2);
System.out.println(divide);//除
}
}
public class BigDecimal_ {
public static void main(String[] args) {
//當我們需要保存一個精度很高的數時,double 不夠用
//可以是 BigDecimal
// double d = 1999.11111111111999999999999977788d;
// System.out.println(d);
BigDecimal bigDecimal = new BigDecimal("1999.11");
BigDecimal bigDecimal2 = new BigDecimal("3");
System.out.println(bigDecimal);
//解讀
//1. 如果對 BigDecimal進行運算,比如加減乘除,需要使用對應的方法
//2. 創建一個需要操作的 BigDecimal 然后調用相應的方法即可
System.out.println(bigDecimal.add(bigDecimal2));
System.out.println(bigDecimal.subtract(bigDecimal2));
System.out.println(bigDecimal.multiply(bigDecimal2));
//System.out.println(bigDecimal.divide(bigDecimal2));//可能拋出異常ArithmeticException
//在調用divide 方法時,指定精度即可. BigDecimal.ROUND_CEILING
//如果有無限循環小數,就會保留 分子 的精度
System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
}
}
11.11 日期類
11.11.1 第一代日期類
Date:精確到毫秒,代表特定的瞬間SimpleDateFormat:格式和解析日期的類
SimpleDateFormat格式化和解析日期的具體類。它允許進行格式化(日期 -> 文本)、解析(文本 -> 日期)和規范化。- 應用實例
Date_java
(右側含日期或時間元素表示的表格,如 Era 標志符、年、年中的月份等對應表示和示例 )
public class Date01 {
public static void main(String[] args) throws ParseException {
//解讀
//1. 獲取當前系統時間
//2. 這里的Date 類是在java.util包
//3. 默認輸出的日期格式是國外的方式, 因此通常需要對格式進行轉換
Date d1 = new Date(); //獲取當前系統時間
System.out.println("當前日期=" + d1);
Date d2 = new Date(9234567); //通過指定毫秒數得到時間
System.out.println("d2=" + d2); //獲取某個時間對應的毫秒數
//
//解讀
//1. 創建 SimpleDateFormat對象,可以指定相應的格式
//2. 這里的格式使用的字母是規定好,不能亂寫
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
String format = sdf.format(d1); // format:將日期轉換成指定格式的字符串
System.out.println("當前日期=" + format);
//解讀
//1. 可以把一個格式化的String 轉成對應的 Date
//2. 得到Date 仍然在輸出時,還是按照國外的形式,如果希望指定格式輸出,需要轉換
//3. 在把String -> Date , 使用的 sdf 格式需要和你給的String的格式一樣,否則會拋出轉換異常
String s = "1996年01月01日 10:20:30 星期一";
Date parse = sdf.parse(s);
System.out.println("parse=" + sdf.format(parse));
}
}
11.11.2 第二代日期類
- 第二代日期類,主要就是
Calendar類(日歷)。public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar> Calendar類是一個抽象類,它為特定瞬間與一組諸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日歷字段之間的轉換提供了一些方法,并為操作日歷字段(例如獲得下星期的日期)提供了一些方法。
public class Calendar_ {
public static void main(String[] args) {
//解讀
//1. Calendar是一個抽象類, 并且構造器是private
//2. 可以通過 getInstance() 來獲取實例
//3. 提供大量的方法和字段提供給程序員
//4. Calendar沒有提供對應的格式化的類,因此需要程序員自己組合來輸出(靈活)
//5. 如果我們需要按照 24小時進制來獲取時間, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY
Calendar c = Calendar.getInstance(); //創建日歷類對象//比較簡單,自由
System.out.println("c=" + c);
//2.獲取日歷對象的某個日歷字段
System.out.println("年:" + c.get(Calendar.YEAR));
// 這里為什么要 + 1, 因為Calendar 返回月時候,是按照 0 開始編號
System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
System.out.println("小時:" + c.get(Calendar.HOUR));
System.out.println("分鐘:" + c.get(Calendar.MINUTE));
System.out.println("秒:" + c.get(Calendar.SECOND));
//Calender 沒有專門的格式化方法,所以需要程序員自己來組合顯示
System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) +
" " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );
}
}
11.11.3 第三代日期類
前面兩代日期類的不足分析
JDK 1.0中包含了一個java.util.Date類,但是它的大多數方法已經在JDK 1.1引入Calendar類之后被棄用了。而Calendar也存在問題是:
- 可變性:像日期和時間這樣的類應該是不可變的。
- 偏移性:
Date中的年份是從1900開始的,而月份都從0開始。 - 格式化:格式化只對
Date有用,Calendar則不行。 - 此外,它們也不是線程安全的,不能處理閏秒等(每隔2天,多出1s)。
第三代日期類核心
LocalDate(日期/年月日)、LocalTime(時間/時分秒)、LocalDateTime(日期時間/年月日時分秒) JDK8加入LocalDate只包含日期,可以獲取日期字段LocalTime只包含時間,可以獲取時間字段LocalDateTime包含日期+時間,可以獲取日期和時間字段
案例演示:LocalDate_java
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
ldt.getYear();ldt.getMonthValue();ldt.getMonth();ldt.getDayOfMonth();
ldt.getHour();ldt.getMinute();ldt.getSecond();
public class LocalDate_ {
public static void main(String[] args) {
//第三代日期
//解讀
//1. 使用now() 返回表示當前日期時間的 對象
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
System.out.println(ldt);
//2. 使用DateTimeFormatter 對象來進行格式化
// 創建 DateTimeFormatter對象
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = dateTimeFormatter.format(ldt);
System.out.println("格式化的日期=" + format);
System.out.println("年=" + ldt.getYear());
System.out.println("月=" + ldt.getMonth());
System.out.println("月=" + ldt.getMonthValue());
System.out.println("日=" + ldt.getDayOfMonth());
System.out.println("時=" + ldt.getHour());
System.out.println("分=" + ldt.getMinute());
System.out.println("秒=" + ldt.getSecond());
LocalDate now = LocalDate.now(); //可以獲取年月日
LocalTime now2 = LocalTime.now();//獲取到時分秒
//提供 plus 和 minus方法可以對當前時間進行加或者減
//看看890天后,是什么時候 把 年月日-時分秒
LocalDateTime localDateTime = ldt.plusDays(890);
System.out.println("890天后=" + dateTimeFormatter.format(localDateTime));
//看看在 3456分鐘前是什么時候,把 年月日-時分秒輸出
LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
System.out.println("3456分鐘前 日期=" + dateTimeFormatter.format(localDateTime2));
}
}
11.11.4 DateTimeFormatter 格式日期類
類似于SimpleDateFormat
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(格式);
String str = dtf.format(日期對象);
案例演示:
LocalDateTime ldt = LocalDateTime.now();
//關于 DateTimeFormatter 的各個格式參數,需要看jdk8的文檔.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH時mm分ss秒");
String strDate = dtf.format(ldt);
11.11.5 Instant 時間戳
類似于Date,提供了一系列和Date類轉換的方式
-
Instant --> Date:
Date date = Date.from(instant); -
Date --> Instant:
Instant instant = date.toInstant();
案例演示:
Instant now = Instant.now();
System.out.println(now);
Date date = Date.from(now);
Instant instant = date.toInstant();
public class Instant_ {
public static void main(String[] args) {
//1.通過 靜態方法 now() 獲取表示當前時間戳的對象
Instant now = Instant.now();
System.out.println(now);
//2. 通過 from 可以把 Instant轉成 Date
Date date = Date.from(now);
//3. 通過 date的toInstant() 可以把 date 轉成Instant對象
Instant instant = date.toInstant();
}
}
11.11.6 第三代日期類更多方法
LocalDateTime類MonthDay類:檢查重復事件- 是否是閏年
- 增加日期的某個部分
- 使用
plus方法測試增加時間的某個部分 - 使用
minus方法測試查看一年前和一年后的日期 - 其他的方法,就不說,使用的時候,自己查看API使用即可
11.12 本章作業
1. 編程題 Homework01.java
(1) 將字符串中指定部分進行反轉。比如將"abcdef"反轉為"aedcbf"
(2) 編寫方法 public static String reverse(String str, int start, int end) 搞定
以下是整理后的內容,按“同上”(延續之前的章節替換規則,把原 13 開頭章節調整為 11 開頭 )的格式呈現:
public class Homework01 {
public static void main(String[] args) {
//測試
String str = "abcdef";
System.out.println("===交換前===");
System.out.println(str);
try {
str = reverse(str, -1, 4);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
System.out.println("===交換后===");
System.out.println(str);
}
/**
* (1) 將字符串中指定部分進行反轉。比如將"abcdef"反轉為"aedcbf"
* (2) 編寫方法 public static String reverse(String str, int start , int end) 搞定
* 思路分析
* (1) 先把方法定義確定
* (2) 把 String 轉成 char[] ,因為char[] 的元素是可以交換的
* (3) 畫出分析示意圖
* (4) 代碼實現
*/
public static String reverse(String str, int start, int end) {
//對輸入的參數做一個驗證
//重要的編程技巧分享!!!
//(1) 寫出正確的情況
//(2) 然后取反即可
//(3) 這樣寫,你的思路就不亂
if(!(str != null && start >= 0 && end > start && end < str.length())) {
throw new RuntimeException("參數不正確");
}
char[] chars = str.toCharArray();
char temp = ' '; //交換輔助變量
for (int i = start, j = end; i < j; i++, j--) {
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
//使用chars 重新構建一個String 返回即可
return new String(chars);
}
}
2. 編程題 Homework02.java
輸入用戶名、密碼、郵箱,如果信息錄入正確,則提示注冊成功,否則生成異常對象
要求:
- 用戶名長度為2或3或4
- 密碼的長度為6,要求全是數字(可用
isDigital輔助判斷 ) - 郵箱中包含
@和.,并且@在.的前面
public class Homework02 {
public static void main(String[] args) {
String name = "abc";
String pwd = "123456";
String email = "ti@i@sohu.com";
try {
userRegister(name,pwd,email);
System.out.println("恭喜你,注冊成功~");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* 輸入用戶名、密碼、郵箱,如果信息錄入正確,則提示注冊成功,否則生成異常對象
* 要求:
* (1) 用戶名長度為2或3或4
* (2) 密碼的長度為6,要求全是數字 isDigital
* (3) 郵箱中包含@和. 并且@在.的前面
* <p>
* 思路分析
* (1) 先編寫方法 userRegister(String name, String pwd, String email) {}
* (2) 針對 輸入的內容進行校核,如果發現有問題,就拋出異常,給出提示
* (3) 單獨的寫一個方法,判斷 密碼是否全部是數字字符 boolean
*/
public static void userRegister(String name, String pwd, String email) {
//再加入一些校驗
if(!(name != null && pwd != null && email != null)) {
throw new RuntimeException("參數不能為null");
}
//過關
//第一關
int userLength = name.length();
if (!(userLength >= 2 && userLength <= 4)) {
throw new RuntimeException("用戶名長度為2或3或4");
}
//第二關
if (!(pwd.length() == 6 && isDigital(pwd))) {
throw new RuntimeException("密碼的長度為6,要求全是數字");
}
//第三關
int i = email.indexOf('@');
int j = email.indexOf('.');
if (!(i > 0 && j > i)) {
throw new RuntimeException("郵箱中包含@和. 并且@在.的前面");
}
}
//單獨的寫一個方法,判斷 密碼是否全部是數字字符 boolean
public static boolean isDigital(String str) {
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '9') {
return false;
}
}
return true;
}
}
3. 編程題 Homework03.java
- 編寫Java程序,輸入形式為:
Han shun Ping的人名,以Ping,Han .S的形式打印出來 。其中.S是中間單詞的首字母。 - 例如輸入
“Willian Jefferson Clinton”,輸出形式為:Clinton, Willian .J
public class Homework03 {
public static void main(String[] args) {
String name = "Willian Jefferson Clinton";
printName(name);
}
/**
* 編寫方法: 完成輸出格式要求的字符串
* 編寫java程序,輸入形式為: Han shun Ping的人名,以Ping,Han .S的形式打印
* 出來 。其中.S是中間單詞的首字母
* 思路分析
* (1) 對輸入的字符串進行 分割split(" ")
* (2) 對得到的String[] 進行格式化String.format()
* (3) 對輸入的字符串進行校驗即可
*/
public static void printName(String str) {
if(str == null) {
System.out.println("str 不能為空");
return;
}
String[] names = str.split(" ");
if(names.length != 3) {
System.out.println("輸入的字符串格式不對");
return;
}
String format = String.format("%s,%s .%c", names[2], names[0], names[1].toUpperCase().charAt(0));
System.out.println(format);
}
}
4. 編程題 Homework04.java
輸入字符串,判斷里面有多少個大寫字母,多少個小寫字母,多少個數字
public class Homework04 {
public static void main(String[] args) {
String str = "abcHsp U 1234";
countStr(str);
}
/**
* 輸入字符串,判斷里面有多少個大寫字母,多少個小寫字母,多少個數字
* 思路分析
* (1) 遍歷字符串,如果 char 在 '0'~'9' 就是一個數字
* (2) 如果 char 在 'a'~'z' 就是一個小寫字母
* (3) 如果 char 在 'A'~'Z' 就是一個大寫字母
* (4) 使用三個變量來記錄 統計結果
*/
public static void countStr(String str) {
if (str == null) {
System.out.println("輸入不能為 null");
return;
}
int strLen = str.length();
int numCount = 0;
int lowerCount = 0;
int upperCount = 0;
int otherCount = 0;
for (int i = 0; i < strLen; i++) {
if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
numCount++;
} else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
lowerCount++;
} else if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
upperCount++;
} else {
otherCount++;
}
}
System.out.println("數字有 " + numCount);
System.out.println("小寫字母有 " + lowerCount);
System.out.println("大寫字母有 " + upperCount);
System.out.println("其他字符有 " + otherCount);
}
}

浙公網安備 33010602011771號