1、设计一个可以执行基本数学运算(加减乘除)的计算器程序
功能描述:
用户输入两个数字、一个运算符(+、-、*、/)。
根据所选运算符执行相应的数学运算,显示运算结果。
import java.util.Scanner;public class TestDemo1 {public static void main(String[] args) {// 键盘输入两个数字,键盘输入一个运算符,完成对应的运算Scanner sc = new Scanner(System.in);System.out.println("请输入数字a:");double a = sc.nextDouble();System.out.println("请输入数字b:");double b = sc.nextDouble();System.out.println("请输入运算符(+、-、*、/)");String op = sc.next();System.out.println(calc(a, b, op));}public static double calc(double a, double b, String op) {switch (op) {case "+":return a + b;case "-":return a - b;case "*":return a * b;case "/":if (b == 0) {System.out.println("除数不能为0");}return a / b;default:System.out.println("运算符输入错误");}return 0;}
}
2、猜数字小游戏
需求:
随机生成一个1-100之间的数据,提示用户猜测,猜大提示过大,猜小提示过小,直到猜中结束游戏。
import java.util.Random;
import java.util.Scanner;public class TestDemo2 {public static void main(String[] args) {//猜数字小游戏//int number = (int)(Math.random()*100+1);Random r = new Random();int number = r.nextInt(100)+1;guess(number);}public static void guess(int number){Scanner sc = new Scanner(System.in);int userGuess = 0;while(userGuess != number){System.out.println("请输入猜测数字:");userGuess = sc.nextInt();if(userGuess < number){System.out.println("猜小了");}else if(userGuess > number){System.out.println("猜大了");}else{System.out.println("恭喜你猜对了");}}}
}
3、验证码
需求:开发一个程序,可以生成指定位数的验证码,每位可以是数字,大小写字母
public class TestDemo3 {public static void main(String[] args) {//开发验证码//1、调用一个方法返回执行位数的验证码,每位只能是数字或者大写字母或者小写字母System.out.println(getCode(4));System.out.println(getCode(6));}private static String getCode(int i) {//2、定义一个字符串变量用于记录生产的验证码String code = "";//3、循环i次,生成一个验证码for (int j = 0; j < i; j++) {//j = 0 1 2 3//4、为当前位置随机生成一个数字或者大写字母或者小写字母 数字0 /大写1 /小写2//随机一个 0 或者 1 或者 2表示当前位置随机的字符类型int type = (int)(Math.random() * 3); //0 1 2//5、使用switch判断当前位置随机的字符类型switch (type) {case 0://生成数字int num = (int)(Math.random() * 10);code += num;break;case 1://生成大写字母 A-Z 'A'65 'Z'65+25int uppercase = (int)(Math.random() * 26 + 'A');code += (char)uppercase;break;case 2://生成小写字母int lowercase = (int)(Math.random() * 26 + 'a');code += (char)lowercase;break;}}return code;}
}
4、找素数
判断101-200之间有多少个素数,并输出所有素数,统计素数个数
说明:除了1和它本身之外,不能被其他正整数整除,就叫素数。
public class TestDemo4 {public static void main(String[] args) {//判断101-200之间有多少个素数,并输出所有素数//说明:除了1和它本身之外,不能被其他正整数整除,就叫素数。//1、遍历101-200int count = 0;for (int i = 101; i <= 200; i++) {//2、每遍历到一个数字,判断这个数字是否是素数,是则输出if(isPrime(i)){System.out.print(i + " ");}}System.out.println("素数的个数为:" + count);}public static boolean isPrime(int number) {//定义一个循环从2开始找到该数的一半,如果能被整除,则不是素数//如果没有找到,那么number是素数for (int i = 2; i <= number / 2; i++) {//3、判断number是否能被i整除if (number % i == 0) {return false;}}return true;//是素数}
}