目錄
獲取數值數組中第二大的數的索引值,例如:數值數組爲 {2,5,8,8,3,7,9,4,1,6,9}, 結果爲 2
統計一個txt文本文件中字母和數字的數量
思路:1、按行讀取這個文件
2、遍歷每一行數據
3、將一行的數據的每一個數據轉換爲char類型
4、根據char字符判斷是數字或者字母,若是將數量加一
5、關閉流
示例如下:
public static void main(String[] args) {
try {
File file = new File("C:/tools/aaa.txt");
FileReader fr = new FileReader(file);
BufferedReader bf = new BufferedReader(fr);
String str = bf.readLine();
int num = 0;
int word = 0;
while (str != null) {
for (int i = 0; i < str.length(); i++) {
char s = str.charAt(i);
if (('A' <= s && s <= 'Z') || ('a' <= s && s <= 'z')) {
word++;
}
if ('0' <= s && s <= '9') {
num++;
}
}
str = bf.readLine();
}
bf.close();
fr.close();
System.out.println("字母的數量: "+word+", 數字的數量:"+num);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
獲取數值數組中第二大的數的索引值,例如:數值數組爲 {2,5,8,8,3,7,9,4,1,6,9}, 結果爲 2
思路:
假設前兩個數爲最大數和第二大數
循環數組依次拿出數值和前兩個數進行 比較
若是小於等於第二大數,不做改變,再往下獲取值比較
若是等於最大值也不做改變
若是小於最大值,將此時的值與第二大值和索引進行交換
若是大於最大值,將原來最大值與原第二大值交換,將原最大值與此時值交換
/**
* 獲取第二大的數的索引
* @param array
* @return
*/
public static int getIndex(int[] array) {
int big = array[0] > array[1] ? array[0]:array[1];//定義最大值
int second = array[0] > array[1] ? array[1]:array[0];//定義第二大值
int sindex = array[0] > array[1] ? 1:0;//定義第二大值索引
int bindex = array[0] > array[1] ? 0:1;//定義最大值索引
for (int i = 2; i <array.length; i++) {//循環獲取每個數值,與最大數,第二大數比較
if (array[i] <= second) {
} else {
if (array[i] == big) {
}
if (array[i] < big) {
second = array[i];
sindex = i;
}
if (array[i] > big) {
second = big;
big = array[i];
sindex = bindex;
bindex = i;
}
}
}
return sindex;
}
public static void main(String[] args) {
int[] array = {2,5,8,8,3,7,9,4,1,6,9};
int result = getIndex(array);
System.out.println(result);
}
兩個有序數據合併排序
public static void main(String[] args) {
int[] a = {1,3,5,9,10,15};
int[] b = {0,4,7,19};
List<Integer> list = new ArrayList<>();
getSortedJoin(a,b,list);
}
/**
* 兩個有序數組合並排序
* @param a
* @param b
* @param list
*/
private static void getSortedJoin(int[] a, int[] b, List<Integer> list) {
int i = 0;//a數組索引
int j = 0;//b數組索引
int compare = 0;//a b數組兩兩比較後比較大的值
//1、若a、b數組都沒有將數據全部取出
while (i<a.length && j<b.length) {
if (a[i]>b[j]) {
list.add(b[j]);
compare = a[i];
j++;
} else {
list.add(a[i]);
compare = b[j];
i++;
}
}
//2、若是a數據已經將所有的數據放入了list中,b數組沒有全部取出
while (i==a.length && j<b.length) {
list.add(b[j]);
j++;
}
//3、若是b數據已經將所有的數據放入了list中,a數組沒有全部取出
while (i<a.length && j==b.length) {
list.add(a[i]);
i++;
}
System.out.println(list);
}