- 实现一个方法(计算一个只有加减运算的表达式的值),方法的输入参数是一个字符串,例如 “9+9+2-3+2-1”,该方法的返回值为int,结果为18.
public int getNum(String exp){
//String exp = "8+6-2-4-2+2";
String sign = exp.substring(0,1);
String tmp = "+";
if(!sign.equals("-")){
exp = tmp+exp;
}
//首先找出 + ,使用正则表达式
String pattern = "\\+[0-9]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(exp);
int num = 0;
while(m.find()){
num = num+Integer.parseInt(m.group().substring(1,m.group().length()));
}
// 再找出 - 号,使用
String pattern1 = "-[0-9]+";
Pattern p = Pattern.compile(pattern1);
Matcher m1 = p.matcher(exp);
while (m1.find()){
num= num-Integer.parseInt(m1.group().substring(1,m1.group().length()));
}
System.out.println(num);
return num;
}
- 实现一个方法,求一维数组(int型)中第二大的数值;
方法1:重新排序数组,得到第二大的数
@Test
public void getSecondNum() {
int[] arr = {12, 31, 41, 23};
for (int i = 0; i < arr.length - 1; i++) {//外层循环控制排序趟数
for (int j = 0; j < arr.length - 1 - i; j++) {//内层循环控制每一趟排序多少次
if ( arr[j] < arr[j + 1] ) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
方法2:通过设置两个变量来进行判断:
@Test
public void getSecondNum() {
int[] arr = {12, 31, 41, 23,9,40,-32};
int max=arr[0];
int min = -Integer.MIN_VALUE;
for(int i = 0;i<arr.length ;i++){
if(arr[i] == max){
continue;
}
if(arr[i] > max){
min = max; // 将上一次循环得到的最大值作为第二大值
max = arr[i];
}else{
if(arr[i] > min){
min = arr[i];
}
}
System.out.println(max+"..."+min);
}
}
- 求出姓名重复的记录;
使用关键字 group by name having conunt > 1
select first_name,last_name,count(first_name) as cont from contacts GROUP BY first_name HAVING cont > 1;
select * from contacts b where ( (select COUNT(first_name) from contacts where first_name = b.first_name ) > 1 ) ORDER BY b.first_name DESC - 求不同分数区间的学生人数 score在60-70,70-80,80-90,90-100的人数
select sum(case when score > 60 and score < 70
then 1 else 0 end ) as "中等",
sum(case when score > 70 and score < 80
then 1 else 0 end) as "良好",
sum(case when score < 90 and score > 80
then 1 else 0 end) as "优秀",
sum(case when score < 100 and score < 90
then 1 else 0 end) as "天秀"
from scoreInfo;
- 斐波那契数列
public static int test3(int n) {
if (n == 1 || n == 2) {
return 1;
}else {
return test3(n-1) + test3(n-2);
}
}