冒泡排序:
for(int i = 0 ; i < size-1; i ++)
{
for(int j = 0 ;j < size-1-i ; j++)
{
if(arr[j] > arr[j+1]) //交换两数位置
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
选择排序
for (int i = 0; i < chars.length; i++) {
for (int j = i; j < chars.length; j++) {
if (chars[i]>chars[j]){
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
package com.autumn;
public class Demo01 {
public static int tz(int i){
if( i == 1 || i == 2 ){
return 1;
}else{
return tz(i-1) + tz(i-2);
}
}
public static void main(String[] args) {
for (int i = 1; i <= 12; i++) {
System.out.println("第"+i+"月兔子总数:"+Demo01.tz(i));
}
}
}
判断101-200之间有多少个素数,并输出所有素数。
package com.autumn;
import java.util.ArrayList;
public class Demo02 {
public static void main(String[] args) {
int num = 0;
for (int i = 101; i <= 200; i++) {
for (int j = 2; j <= i; j++){
if (i%j==0 && i!=j){
//不是质数
break;
}
if (i==j){
//是质数
System.out.println("指数:"+i);
num++;
}
}
}
System.out.println("指数个数:"+num);
}
}
打印出所有的"水仙花数(narcissus
number)",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
package com.autumn;
public class Demo03 {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
int gw = i%10;
int sw = i/10%10;
int bw = i/100;
if ((gw*gw*gw+sw*sw*sw+bw*bw*bw) == i){
System.out.println("水仙花数为:"+i);
}
}
}
}
题目:将一个正整数分解质因数。例如:输入90,打印出90=233*5
package com.autumn;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
System.out.println("请输入一个你要分解的正整数:");
Scanner scanner=new Scanner(System.in);
int n =scanner.nextInt();
System.out.println();
System.out.print(n+"=");
for(int i=2;i<=n;i++){
while (n%i==0 && n!=i){
n=n/i;
System.out.print(i+"*");
}
if(n==i){
System.out.println(i);
break;
}
}
}
}
利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
package com.autumn;
import java.util.Scanner;
public class Demo05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true){
System.out.println("请输入成绩:");
int cj = sc.nextInt();
String pj = null;
pj = cj >= 90 ? "A" : cj>=60 && cj<=89 ? "B" : "C";
System.out.println("评分:"+pj);
}
}
}



