java练习(7.3)
练习一
题目:
方法一:直接通过main方法来实现(不使用其他方法)
代码
1 import java.util.Scanner; 2 3 public class lianxi { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 System.out.println("输入机票原价"); 7 int ticket = sc.nextInt(); 8 System.out.println("输入仓位 0--头等舱 1--经济舱"); 9 int seat = sc.nextInt(); 10 System.out.println("输入当前月份"); 11 int month = sc.nextInt(); 12 if (month >= 5 && month <= 10) { 13 if (seat == 0) { 14 ticket = (int) (ticket * 0.9); 15 } else { 16 ticket = (int) (ticket * 0.85); 17 } 18 } else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)) { 19 if (seat == 0) { 20 ticket = (int) (ticket * 0.7); 21 } else { 22 ticket = (int) (ticket * 0.65); 23 } 24 } else { 25 System.out.println("年份有误"); 26 return; 27 } 28 System.out.println("打折后票价为:" + ticket + "元"); 29 } 30 }
方法二:使用方法来解决问题(提高代码的复用率)
1 import java.util.Scanner; 2 3 public class lianxi { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 System.out.println("输入机票原价"); 7 int ticket = sc.nextInt(); 8 System.out.println("输入仓位 0--头等舱 1--经济舱"); 9 int seat = sc.nextInt(); 10 System.out.println("输入当前月份"); 11 int month = sc.nextInt(); 12 ticket = getTicket(ticket, seat, month); 13 System.out.println("打折后票价为:" + ticket + "元"); 14 } 15 16 public static int getTicket(int ticket, int seat, int month) { 17 if (month >= 5 && month <= 10) { 18 if (seat == 0) { 19 ticket = (int) (ticket * 0.9); 20 } else { 21 ticket = (int) (ticket * 0.85); 22 } 23 } else if ((month >= 1 && month <= 4) || (month >= 11 && month <= 12)) { 24 if (seat == 0) { 25 ticket = (int) (ticket * 0.7); 26 } else { 27 ticket = (int) (ticket * 0.65); 28 } 29 } else { 30 System.out.println("年份有误"); 31 32 } 33 return ticket; 34 } 35 }
总结:遇到一段代码需要使用多次时,将其定义为一个方法,可以提高代码的复用率;
练习二
题目:
代码:
1 import java.util.Scanner; 2 3 public class lianxi { 4 public static void main(String[] args) { 5 6 int count = 0; 7 for (int i = 101; i <= 200; i++) { 8 boolean flag = true; 9 //每判断完一个数字后,要将标志值flag置为true,用来下一次判断----如果不这样操作,后续flag值恒为false,不再有意义 10 for (int j = 2; j < i; j++) { 11 if (i % j == 0) { 12 flag = false; 13 break; 14 } 15 } 16 if (flag) { 17 count++; 18 System.out.println(i + "是质数"); 19 } 20 } 21 System.out.println("一共有" + count + "个质数"); 22 } 23 }
总结:注意细节问题,每次判断完一个数字之后,需要将标志值重新置为true,以便判断下一个数字时使用;
练习三
题目:
代码:
1 import java.util.Random; 2 3 public class lianxi { 4 public static void main(String[] args) { 5 Random r = new Random(); 6 char[] chs = new char[52]; 7 String result = ""; 8 for(int i=0;i<52;i++){ 9 if(i<=25){ 10 chs[i]=(char)('a'+i); //添加小写字母 11 } 12 else{ 13 chs[i]=(char)('A'+i-26); //添加大写字母 14 } 15 } 16 for(int i=0;i<4;i++) { 17 int index = r.nextInt(chs.length); 18 result = result + chs[index]; //将随机得来的四个字符拼接起来 19 } 20 int number=r.nextInt(10); 21 result=result+number; //与数字进行拼接 22 System.out.println(result); 23 } 24 }