1. 程式人生 > >Java基礎-------排序,Object類,String類,Arrays類,StringBuffer類

Java基礎-------排序,Object類,String類,Arrays類,StringBuffer類

在這裡插入圖片描述

例1: 鍵盤輸入:abcde 列印輸出:edcba public class demo { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println(“請輸入一串字串”); String str=sc.next(); String s=new StringBuffer(str).reverse().toString(); System.out.println(s); } } 在這裡插入圖片描述 例2:請編寫程式,統計鍵盤錄入的字串中包含大寫字母、小寫字母、數字的個數,並測試。 public class demo { public static void main(String[] args) { Scanner sc=new Scanner(

System.in); System.out.println(“請輸入字串”); String s1=sc.next(); int da=0; int xiao=0; int num=0; for(int i=0;i<s1.length();i++) { char c=s1.charAt(i); if(c>=‘a’&&c<=‘z’) { xiao++; }else if(c>=‘A’&&c<=‘Z’) { da++; }else { num++; } } System.out.println(“大寫字母有”+da+“個”); System.out.println(“小寫字母有”+xiao+“個”); System.out.println(“數字有”+num+“個”); } }在這裡插入圖片描述
氣泡排序: public class Test { public static void main(String[] args) { int[] arr = {24, 69, 80, 57, 13} ; System.out.print("排序前: "); print(arr) ; bubbleSort2(arr); System.out.print(“排序後: “); print(arr) ; } private static void bubbleSort2(int[] arr) { for(int x = 0 ; x < arr.length - 1 ; x++){ for(int y = 0 ; y < arr.length - 1 - x ; y++){ if(arr[y] > arr[y + 1]){ int temp = arr[y] ; arr[y] = arr[y+1]; arr[y+1] = temp ; } } } } public static void print(int[] arr){ System.out.print(”[”); for(int x = 0 ; x < arr.length ; x++){ if(x == arr.length - 1){ System.out.println(arr[x] + “]”); }else { System.out.print(arr[x] + ", "); } } } }在這裡插入圖片描述
二分查詢: public class binarySearch { public static void main(String[] args) { int[] arr = {13, 24, 57, 69, 80} ; int index = binarySearch2(arr , 80) ; System.out.println("index: " + index); } private static int binarySearch2(int[] arr, int value) { int minIndex = 0 ; int maxIndex = arr.length - 1 ; while(minIndex <= maxIndex){ // 計算出中間索引 int midIndex = (minIndex + maxIndex) >>> 1 ; // 比較 if(arr[midIndex] == value){ return midIndex ; }else if(arr[midIndex] > value){ maxIndex = midIndex - 1 ; }else if(arr[midIndex] < value){ minIndex = midIndex + 1 ; } } return -1; } }在這裡插入圖片描述