清明在家,无聊,把一些经典的算法总结了一下.
一、求最大,最小值
Scanner input=new Scanner(System.in);
int[] a={21,31,4,2,766,345,2,34};
//这里防止数组中有负数,所以初始化的时候给的数组中的第一个数。
int max=a[0];
int min=a[0];
for (int i = 0; i < a.length; i++) {
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
System.out.println("最大的数是:"+max);
System.out.println("最小的值是:"+min);
二、1--100之间的质数(什么叫质数,就是只能被1和本身能除尽的数)
//因为1不是质数,所以排除在外
for (int i = 2; i < 100; i++) {
boolean a=true;
for (int j = 2; j < i/2+1; j++) {
if(i%j==0){
a=false;
break;
}
}
if(a)
System.out.print(i+" ");
}
三、斐波纳契数列(如:1,1,2,3,5,8,13。。。)
int a=1;
int b=0;
for (int i = 1; i <= 10; i++) {
a=a+b;
System.out.print(a+" ");
b=a+b;
System.out.print(b+" ");
}
四、输入一个正整数,倒着打印出来(如:123456789,打印出来是:987654321)
Scanner input=new Scanner(System.in);
int a=input.nextInt();
for (int i = 1; i < 999; i++) {
if(a!=0){
System.out.print(a%10+" ");
a=a/10;
}else{
break;
}
}
五、冒泡排序
int score[] = { 167, 69, 75, 87, 89, 90, 99, 100 };
// 最多做n-1趟排序
for (int i = 0; i < score.length - 1; i++) {
// 对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
for (int j = 0; j < score.length - i - 1; j++) {
// 把小的值交换到后面
if (score[j] > score[j + 1]) {
int temp = score[j];
score[j] = score[j + 1];
score[j + 1] = temp;
}
}
}
System.out.print("最终排序结果:");
for (int a = 0; a < score.length; a++) {
System.out.print(score[a] + "\t");
}
六、在控制台打印日历,平且标出今天
package test;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class HelloString {
public static void main(String[] args) {
// 构建D为当前日期
GregorianCalendar d = new GregorianCalendar();
int today = d.get(Calendar.DAY_OF_MONTH);
int month = d.get(Calendar.MONTH);
// D组为本月的开始日期
d.set(Calendar.DAY_OF_MONTH, 1);
int weekday = d.get(Calendar.DAY_OF_WEEK);
// 一周的第一天是星期日
int firstDayOfWeek = d.getFirstDayOfWeek();
int indent = 0;
while (weekday != firstDayOfWeek) {
indent++;
d.add(Calendar.DAY_OF_MONTH, -1);
weekday = d.get(Calendar.DAY_OF_WEEK);
}
// 打印工作日的名称
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
do {
System.out.printf("%4s", weekdayNames[weekday]);
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
} while (weekday != firstDayOfWeek);
System.out.println();
for (int i = 1; i <= indent; i++)
System.out.print(" ");
d.set(Calendar.DAY_OF_MONTH, 1);
do {
// 打印的一天
int day = d.get(Calendar.DAY_OF_MONTH);
System.out.printf("%3d", day);
// 带*标记当前日期
if (day == today)
System.out.print("*");
else
System.out.print(" ");
// 先进的第二天
d.add(Calendar.DAY_OF_MONTH, 1);
weekday = d.get(Calendar.DAY_OF_WEEK);
// 从本周开始新的一行
if (weekday == firstDayOfWeek)
System.out.println();
} while (d.get(Calendar.MONTH) == month);
// 循环退出时,D是下个月的1天
// 如果需要打印的最终行
if (weekday != firstDayOfWeek)
System.out.println();
}
}
先写这么多,累啊,休息休息。