Java初阶入门练习第二弹
数字9 出现的次数
public static void main(String[] args) {
int count = 0;
for (int i = 0; i <= 100; i++) {
if(i % 10 == 9) {
count++;
}else if(i / 10 == 9) {
count++;
}
}
System.out.println(count);
}
打印X形图案
多组输入,一个整数(2~20),表示输出的行数,也表示组成“X”的反斜线和正斜线的长度。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(i == j || i + j == n - 1) {
System.out.print("*");
}else {
System.out.print(" ");
}
}
System.out.println();
}
}
计算分数的值
计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。
public static double fun1() {
double sum = 0;
int flg = 1;
for (int i = 1; i <= 100; i++) {
sum = sum + 1.0/i * flg;
flg = -flg;
}
return sum;
}
public static void main(String[] args) {
double d = fun1();
System.out.println(d);
}
输出一个整数的每一位
public static void func2(int n) {
while(n != 0) {
System.out.println(n % 10);
n /= 10;
}
}
public static void main(String[] args) {
func2(123);
}
模拟登陆
public static void login() {
int count = 3;
Scanner scanner = new Scanner(System.in);
while(count != 0) {
System.out.println("请输入你的密码: ");
String passworld = scanner.nextLine();
if(passworld.equals("123456")) {
System.out.println("登陆成功!");
break;
}else {
count--;
System.out.println("你还有"+count+"次机会!");
}
}
}
public static void main(String[] args) {
login();
}
找最大值
public static int max(int a,int b) {
return a > b ? a : b;
}
public static int max(int a,int b, int c) {
int tmp = max(a,b);
return max(tmp,c);
}
public static void main(String[] args) {
System.out.println(max(1, 2, 3));
}
斐波那契数列
public class Measure {
public static int fib(int n) {
if(n == 1 || n == 2) {
return 1;
}
int f1 = 1;
int f2 = 2;
int f3 = 0;
for (int i = 3; i <= n; i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
public static void main(String[] args) {
System.out.println(fib(1));
System.out.println(fib(2));
System.out.println(fib(3));
System.out.println(fib(4));
System.out.println(fib(5));
}
求和的重载
public static int sum(int a,int b) {
return a+b;
}
public static double sum(double a,double b,double c) {
return a+b+c;
}
汉诺塔问题
public static void hannuota(int n,char pos1,char pos2,char pos3) {
if(n == 1) {
move(pos1,pos3);
return;
}
hannuota(n-1,pos1,pos3,pos2);
move(pos1,pos3);
hannuota(n-1,pos2,pos1,pos3);
}
public static void move(char pos1,char pos2) {
System.out.print(pos1 + "->" + pos2 + " ");
}
public static void main(String[] args) {
hannuota(1,'A','B','C');
System.out.println();
hannuota(2,'A','B','C');
System.out.println();
hannuota(3,'A','B','C');
System.out.println();
}
结果