几个比较基础的题目,夯实基础!
求n! (n-1)! (n-2)! ……… 1!(多组输入)
代码语言:javascript复制 public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int i = 1;
int ret = 1;
int sum=0;
while (i<=n) {
ret *= i;
sum = ret;
i ;
}
System.out.println(sum);
}
do{ 循环语句; }while(循环条件); 先执行循环语句, 再判定循环条件.
猜数字游戏
代码语言:javascript复制import java.util.Random;
import java.util.Scanner;
public class GuessNumbers {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Random random = new Random();
int randNum = random.nextInt(100);[0-99]
while (true) {
System.out.println("请输入数字:");
int num = scan.nextInt();
if (num < randNum)
System.out.println("猜小了");
else if (num > randNum) {
System.out.println("猜大了");
} else {
System.out.println("恭喜你,猜对了");
break;
}
}
}
}
根据年龄, 来打印出当前年龄的人是少年(低于18), 青年(19-28), 中年(29-55), 老年(56以上)
代码语言:javascript复制import java.util.Scanner;
public class JudgeAge {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n=scanner.nextInt();
if (n <= 18) {
System.out.println("少年");
} else if (n < 28) {
System.out.println("青年");
} else if (n <= 55) {
System.out.println("中年");
} else {
System.out.println("老年");
}
}
}
}
打印 1 - 100 之间所有的素数
代码语言:javascript复制public class PrintPrimeNum {
public static void main(String[] args) {
int count = 0;
int j = 0;
for (int i = 1; i <= 100; i = 2) {
for (j = 2; j <= Math.sqrt(i); j ) {
if (i % j == 0) {
break; //i就不是素数了
}
}
if (j > Math.sqrt(i)) {
System.out.print(i " ");
count ;
}
//每行打印6个数字
if (count % 6 == 0) {
System.out.println();
}
}
}
}
最大公约数(辗转相除法)
代码语言:javascript复制import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int a=scanner.nextInt();
int b=scanner.nextInt();
while (a % b != 0) {
int c = a % b;
a = b;
b = c;
}
System.out.println(b);
}
}
}
输入密码
代码语言:javascript复制import java.util.Scanner;
public class Password {
public static void main(String[] args) {
int n = 3;
while (n != 0) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入密码:");
String str=scanner.nextLine();
if (str.equals("123456")) {
System.out.println("密码正确");
break;
}
n--;
if (n == 0) {
System.out.println("你已经失去机会");
break;
}
System.out.println("你还有" n "次机会");
}
}
}
do while 循环
先执行在判断
代码语言:javascript复制 public static void main(String[] args) {
int i = 0;
int sum=0;
do {
sum = i;
i ;
} while (i<=10);
System.out.println(sum);
}
只有先夯实基础,才能更好的学习下去!