Java简单题
【摘要】 几个比较基础的题目,夯实基础!求n!+(n-1)!+(n-2)!+………+1!(多组输入) public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner...
几个比较基础的题目,夯实基础!
求n!+(n-1)!+(n-2)!+………+1!(多组输入)
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(循环条件); 先执行循环语句, 再判定循环条件.
猜数字游戏
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以上)
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 之间所有的素数
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();
}
}
}
}
复制代码
最大公约数(辗转相除法)
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);
}
}
}
复制代码
输入密码
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 循环
先执行在判断
public static void main(String[] args) {
int i = 0;
int sum=0;
do {
sum += i;
i++;
} while (i<=10);
System.out.println(sum);
}
复制代码
只有先夯实基础,才能更好的学习下去!
欢迎点赞收藏关注,感谢大家的支持!
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)