oo前三次作业总结
一:总结
前三次的作业其实偏简单,其中主要考察的还是对基础部分的掌握,除了菜单系列题目,其他题目完全可以不用到“类”来完成。但是这些题目完成的不尽人意,尤其是其中的菜单系列题目,刚开始的还能够完成,随着难度的增加,加之对“类”这一强大工具使用不熟悉,后续的菜单题就强差人意。其他的相对简单的题目也会出现一些错误。
第一次的作业全部都是基础题比较简单,加上有c语言的一些基础,完成较快。使得对后续的作业不够上心,完成效率低,老是拖到快截至才紧赶着完成。
二:作业实现
第一次作业
第一次作业考察主要有以下几点
- 数据的输入,读取,运算,输出;
- 对数据进行处理,判断;
第一次作业中主要还是运用循环,条件语句,数学函数来完成。
以下给出例题及解答:
输入三角形三条边,判断该三角形为什么类型的三角形。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input= new Scanner(System.in); double t; double a=input.nextDouble(); double b=input.nextDouble(); double c=input.nextDouble(); if(a>=1&&a<=200&&b>=1&&b<=200&&c>=1&&c<=200) { if(a>b){t=a;a=b;b=t;} if(a>c){t=a;a=c;c=t;} if(b>c){t=b;b=c;c=t;} if(a+b>c) { if(a==b&&b==c)System.out.print("Equilateral triangle"); else if(a==b&&a*a+b*b-c*c<0.00001)System.out.print("Isosceles right-angled triangle"); else if((a==b||b==c)&&a*a+b*b-c*c>0.00001)System.out.print("Isosceles triangle"); else if(a!=b&&b!=c&&a*a+b*b-c*c<0.00001)System.out.print("Right-angled triangle"); else System.out.print("General triangle"); } else System.out.print("Not a triangle"); } else System.out.print("Wrong Format"); } }
三角形判断的难点在于精确度,在进制转换过程中存在误差,2进制无法准确表示出乘除的关系所以 存在误差,这个时候就需要对误差进行精确判断;这题还有就是要注意不同角的判断。
巴比伦法求平方根近似值
nextGuess = (lastGuess+n/lastGuess)/2
程序初始运行时lastGuess可赋予一个最初的猜测值。当由公式求得的nextGuess和lastGuess相差较大时,把nextGuess的值赋给lastGuess,继续以上过程,直至nextGuess和lastGuess几乎相同,此时lastGuess或者nextGuess就是平方根的近似值。
本题要求:nextGuess和lastGuess的差值小于0.00001时认为两者几乎相同
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner input = new Scanner(System.in); float n=input.nextFloat(); float last=input.nextFloat(); float next=(last+n/last)/2; if(n<0||last<=0){ System.out.println("Wrong Format"); return; } else while(Math.abs(next-last)>=0.00001){ last=next; next=(last+n/last)/2; } System.out.println((float)last); } }
第二次作业开始难度增加,菜单系列1,2开始运用“类”来完成,除了使用类还算法。
第一次的菜单题相对简单,由于对类不熟悉,所以采用了取巧的方法来完成。
菜单计价程序-1
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner input = new Scanner(System.in); String []menu =new String[]{"西红柿炒蛋","清炒土豆丝","麻婆豆腐","油淋生菜"}; int []unit_price={15,12,12,9}; double []Portion={1.0,1.5,2.0}; String dishName; int portion; int total=0; while(true){ int t=0,n; dishName=input.next(); if(dishName.equals("end"))break; portion=input.nextInt(); for(int i=0;i<4;i++) { if(dishName.equals(menu[i])) { t=1; n=i; total=total+(int)((unit_price[i]*Portion[portion-1]*10+5)/10); } } if(t==0) System.out.println(dishName+" does not exist"); } System.out.print(total); } }
菜单系列2的题目难度增加,已经经历在完成,给出的样例完全正确,但是还是有不少的错误。
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner input = new Scanner(System.in); String []menu= new String[1000]; int []price=new int[100]; int []price2=new int[100]; String []Number=new String[100]; String []Order=new String[1000]; double []Portion={1.0,1.5,2.0}; int i=0; int Total=0; String dishname; String number; String q; while(true) { dishname=input.next(); if(dishname.equals("1")){q="1";break;} if(dishname.equals("end")){q="0";break;} int unit_price=input.nextInt(); menu[i]=dishname; price[i]=unit_price; i++; } number=dishname; Number[0]=number; int a=0; while(q.equals("1")) { int t=0,m=0,n; int p=0; String order=input.next(); Order[a]=order; if(order.equals("delete")) { for(int j=0;j<a;j++) { if(number.equals(Number[j])) { m=1; price2[j]=0; } } if(m==0) System.out.println("delete error;"); p=1; } int portion=0; int quantity=0; if(p==0){ portion=input.nextInt(); quantity=input.nextInt(); } for(int j=0;j<i;j++) { if(order.equals(menu[j])) { t=1; n=j; System.out.println(number+" "+order+" "+(int)((price[j]*Portion[portion-1]*quantity*10+5)/10)); price2[a]=(int)((price[j]*Portion[portion-1]*quantity*10+5)/10); } } if(t==0&&!order.equals("delete")) System.out.println(order+" does not exist"); a++; number=input.next(); Number[a]=number; if(number.equals("end"))break; } for(int j=0;j<a;j++) Total=Total+price2[j]; System.out.println(Total); } }
小明走格子
从A点到B点有n个格子,小明现在要从A点到B点,小明吃了些东西,补充了一下体力,他可以一步迈一个格子,也可以一步迈两个格子,也可以一步迈3个格子,也可以一步迈4个格子。请编写程序计算小明从A点到B点一共有多少种走法。

改题的SourceMonitor报表如下:




第三次作业就需要运用到更多的知识点。
在删除重复数字的题目中就使用到了哈希表来节约时间。
import java.util.*; import java.util.HashSet; public class Main{ public static void main(String[] args){ Scanner input=new Scanner(System.in); Set<Integer> set = new HashSet<>(); int []n=new int [100000]; int m = input.nextInt(); int t=0,q=0; int []b=new int[100000]; for(int i=0;i<m;i++) { int a=input.nextInt(); if (set.contains(a)) continue; set.add(a); b[q]=a; q++; } for(int i=0;i<q;i++) { System.out.print(b[i]); if(i!=q-1) System.out.print(" "); } } }
在刚刚写这个题时,虽然能够完成结果正确,可是在输入数字比较多时,处理数据的时间就会大大加长,站用的内存也会超出题目的限制。而哈希表的原理就极大地缩短了时间。
菜单系列3的难度又再次增加,还增加了对时间和餐桌号的要求一下是我的代码及类图:
import java.text.SimpleDateFormat; import java.time.DateTimeException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static boolean isNumeric(String string) { //判断是否为数字 int intValue; try { intValue = Integer.parseInt(string); return true; } catch (NumberFormatException e) { return false; } } public static boolean searchCall(String threeCall) { String []CallNumber=new String[]{"180","181","189","133","135","136"}; for (String s : CallNumber) if (s.equals(threeCall)) return false; return true; } public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss"); //时间模板 Menu menu = new Menu(); HashMap<String ,String>hash=new HashMap<>(); String []customer=new String[30]; int cnt=0; ArrayList<Table> tables = new ArrayList<>(); Scanner input = new Scanner(System.in); String []zhe=new String[]{"不甜","微甜","稍甜","甜"}; String []jin=new String[]{"不酸","微酸","稍酸","酸","很酸"}; String []chuan=new String[]{"不辣","微辣","稍辣","辣","很辣","爆辣"}; int []tastedGrade=new int [100]; int []tastedNumber=new int [100]; String str1 = ""; String str2 = ""; String str3= ""; String []dish; String tb = null; int [][]taste=new int[20][7]; int table_count = 0; int i, flag = 0; int portion = 0, number = 0; //份额,份数 //str2="0";str3=" ";str1=" "; menu.dishes.add(menu.addDish("", 0," ")); while (true) {// 输入菜单 dish=input.nextLine().split(" "); if(dish.length>4&&!dish[0].equals("table")||dish.length==3) { System.out.println("wrong format"); continue; } if(dish.length>4){str1=dish[0]; tb=" "+dish[1]+" "+dish[2]+" "+dish[3]+" "+dish[4]+" "+dish[5]+" "+dish[6]; break;} if(dish.length==4){str1=dish[0];str2=dish[2];str3=dish[1];} if(dish.length==2){str1=dish[0];str2=dish[1];} if(dish.length==1&&dish[0].equals("end")){str1=dish[0];break;} if(dish.length == 1) { System.out.println("wrong format"); continue; } if (dish.length==4) { // 判断这道菜是否为特价菜 if(dish[3].equals("T")&&isNumeric(str2)&&!isNumeric(str3)) { menu.dishes.get(menu.dishes.size() - 1).isT = true; menu.dishes.get(menu.dishes.size() - 1).taste = str3; menu.dishes.get(menu.dishes.size() - 1).name = str1; menu.dishes.get(menu.dishes.size() - 1).price = Integer.parseInt(str2); } else { System.out.println("wrong format"); continue; } } else str3=" "; if(isNumeric(str1)||!isNumeric(str2)) { System.out.println("wrong format"); continue; } // 判断菜谱是否重复输入 for (i = 0; i < menu.dishes.size(); i++) { if (menu.dishes.get(i).equals(str1)) { menu.dishes.get(i).price = Integer.parseInt(str2); flag++; break; } } if (flag == 0) { menu.dishes.add(menu.addDish(str1, Integer.parseInt(str2),str3)); } flag = 0; } boolean first = false; if(str1.equals("end"))return ; while(!str1.equals("end")){ int chuanGrade=0; int chuanNumber=0; int zheGrade=0; int zheNumber=0; int jinGrade=0; int jinNumber=0; String []a; String ord; String call; String useName; Table tab= new Table(); if(first) ord = input.nextLine(); else { ord = tb; first=true; } a=ord.split(" "); str2=a[1]; useName=a[3]; call=a[4]; String threeCall=call.substring(0,3); if(useName.length()>10||call.length()!=11||searchCall(threeCall)){ System.out.println("wrong format"); break; } String[] Date = a[5].split("/"); String[] Time =a[6].split("/"); tab.num = Integer.parseInt(str2); int[] intDate = new int[3]; int[] intTime = new int[3]; for(i=0;i<3;i++) { intDate[i] = Integer.parseInt(Date[i]); intTime[i] = Integer.parseInt(Time[i]); } try { tab.time = LocalDateTime.of(intDate[0],intDate[1],intDate[2],intTime[0],intTime[1],intTime[2]); //时间判断 tables.add(tab); if(!tab.isOpen()) { System.out.println("table " + str2 + " out of opening hours"); do { str1 = input.next(); } while (!str1.equals("end") && !str1.equals("table")); continue; } }catch(DateTimeException e){ System.out.println( tab.num + " date error"); break; } System.out.println("table "+str2+": "); while (true) { str1 = input.next(); if (str1.equals("end")) break; if (str1.equals("table")) break; str2 = input.next(); // 判断是否为代点 if (isNumeric(str2)) { //判断代点桌号是否存在 boolean exist = false; for (Table table : tables) { if (table.num == Integer.parseInt(str1)) { exist = true; break; } } //若存在则完成代点 if(exist) { System.out.print(Integer.parseInt(str2) + " table " +tables.get(table_count).num + " pay for table " + Integer.parseInt(str1) + " "); String str=str1; Record treat = new Record(); str1 = input.next(); treat.ds = menu.dishes.get(menu.searchDish(str1)); if(menu.searchDish(str1)!=-1){ if (menu.dishes.get(menu.searchDish(str1)).isT) { str3 = input.next(); tastedGrade[Integer.parseInt(str)] = Integer.parseInt(str3); } else str3 = " "; }else { System.out.println(str1 + " does not exist"); str1=input.nextLine();continue; } portion = input.nextInt(); number = input.nextInt(); tastedNumber[Integer.parseInt(str)]=number; treat.portion = portion; treat.number = number; System.out.print(treat.getPrice() + "\n"); if(menu.dishes.get(menu.searchDish(str1)).taste.equals("晋菜")) { if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>4){ System.out.println("acidity num out of range :"+jinGrade); str1=input.nextLine(); continue; } taste[Integer.parseInt(str)-1][1] += Integer.parseInt(str3)*number; taste[Integer.parseInt(str)-1][4]+=number; } if(menu.dishes.get(menu.searchDish(str1)).taste.equals("川菜")) { if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>5){ System.out.println("spicy num out of range :"+str3); str1=input.nextLine(); continue; } taste[Integer.parseInt(str)-1][0] += Integer.parseInt(str3)*number; taste[Integer.parseInt(str)-1][3]+=number; } if(menu.dishes.get(menu.searchDish(str1)).taste.equals("浙菜")) { if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>3){ System.out.println("sweetness num out of range :"+str3); str1=input.nextLine(); continue; } taste[Integer.parseInt(str)-1][2] += Integer.parseInt(str3)*number; taste[Integer.parseInt(str)-1][5]+=number; } tables.get(table_count).add(menu, "代点",str2, str1, portion, number); } //若不存在则输出内容 else { System.out.println("Table number :"+Integer.parseInt(str1)+" does not exist"); } } // 若不是代点 else { // 若不为删除订单,则读入份数和大小 if (!str2.equals("delete")) { boolean t=false; if(menu.searchDish(str2)!=-1) { if (menu.dishes.get(menu.searchDish(str2)).isT) { hash.put(str1, menu.dishes.get(menu.searchDish(str2)).taste); str3 = input.next(); portion = input.nextInt(); number = input.nextInt(); tastedGrade[Integer.parseInt(str1)] = Integer.parseInt(str3); tastedNumber[Integer.parseInt(str1)] = number; t = true; if (menu.dishes.get(menu.searchDish(str2)).taste.equals("晋菜")) { if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 4) { System.out.println("acidity num out of range :" + str3); str1 = input.nextLine(); continue; } jinGrade += Integer.parseInt(str3) * number; jinNumber += number; } if (menu.dishes.get(menu.searchDish(str2)).taste.equals("川菜")) { if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 5) { System.out.println("spicy num out of range :" + str3); str1 = input.nextLine(); continue; } chuanGrade += Integer.parseInt(str3) * number; chuanNumber += number; } if (menu.dishes.get(menu.searchDish(str2)).taste.equals("浙菜")) { if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 3) { System.out.println("sweetness num out of range :" + str3); str1 = input.nextLine(); continue; } zheGrade += Integer.parseInt(str3) * number; zheNumber += number; } } else str3 = " "; }else { System.out.println(str2 + " does not exist"); str1=input.nextLine();continue; } if(!t) { portion = input.nextInt(); number = input.nextInt(); } } tables.get(table_count).add(menu, str3,str1, str2, portion, number); if(str2.equals("delete")){ if(hash.get(str1).equals("晋菜")) { jinGrade -= tastedGrade[Integer.parseInt(str1)]; jinNumber -= tastedNumber[Integer.parseInt(str1)]; } if(hash.get(str1).equals("川菜")) { chuanGrade -= tastedGrade[Integer.parseInt(str1)]; chuanNumber -= tastedNumber[Integer.parseInt(str1)]; } if(hash.get(str1).equals("浙菜")) { zheGrade -= tastedGrade[Integer.parseInt(str1)]; zheNumber -= tastedNumber[Integer.parseInt(str1)]; } hash.put(str1,""); } } } taste[table_count][0]=chuanGrade; taste[table_count][1]=jinGrade; taste[table_count][2]=zheGrade; taste[table_count][3]=chuanNumber; taste[table_count][4]=jinNumber; taste[table_count][5]=zheNumber; // 本桌点菜结束,进入下一桌 tables.get(table_count).getSum(); int sum; String str=useName+" "+call+" "+tables.get(table_count).sum; String []b; if(table_count==0)customer[cnt++]=str; else { b = str.split(" "); boolean r=true; for (int l = 0; l < cnt; l++) { String[] c = customer[l].split(" "); if (b[0].equals(c[0])) { sum = Integer.parseInt(c[2]) + Integer.parseInt(b[2]); customer[l] = useName + " " + call + " " + sum; r=false; } } if(r)customer[cnt++]=str; } table_count++; } // 最终输出桌号订单信息 for (i = 0; i < table_count; i++) { if (tables.get(i).isOpen()) { System.out.print("table " + tables.get(i).num + ": " + tables.get(i).origSum+" "+tables.get(i).sum); for(int j=0;j<3;j++){ if(taste[i][j+3]!=0){ if(j==0){ System.out.print(" 川菜 "+taste[i][j+3]+" "+chuan[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]); } if(j==1){ System.out.print(" 晋菜 "+taste[i][j+3]+" "+jin[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]); } if(j==2){ System.out.print(" 浙菜 "+taste[i][j+3]+" "+zhe[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]); } } } System.out.println(); } else System.out.println("table " + tables.get(i).num + " out of opening hours"); } Arrays.sort(customer,0,cnt); for(int j=0;j<cnt;j++) { if(j<cnt-1) System.out.println(customer[j]); else System.out.print(customer[j]); } } } class Dish { //菜单格式 String name; int price; String taste; boolean isT = false; } class Record { //点菜 int orderNum; //序号 Dish ds; //菜品 int portion; //份额 int number; //份数 boolean isDeleted = false; int getPrice() { if (portion == 2) return (int) Math.round(1.5 * ds.price) * number; else if (portion == 3) return 2 * ds.price * number; else return ds.price * number; } } class Menu { //菜单 ArrayList<Dish> dishes = new ArrayList<>(); int searchDish(String dishName) { for (int i = 0; i < dishes.size(); i++) { if (dishName.equals(dishes.get(i).name)) { return i; } } return -1; } Dish addDish(String dishName, int price,String taste) { Dish newDish = new Dish(); newDish.name = dishName; newDish.price = price; newDish.taste=taste; return newDish; } } class Order { //点菜 ArrayList<Record> records = new ArrayList<>(); Record addARecord(String tasteGrade,int orderNum, String dishName, int portion, int number, Menu menu) { Record newRecord = new Record(); newRecord.orderNum = orderNum; newRecord.ds = menu.dishes.get(menu.searchDish(dishName)); newRecord.portion = portion; newRecord.number = number; if(!tasteGrade.equals("代点")) System.out.println(newRecord.orderNum + " " + newRecord.ds.name + " " + newRecord.getPrice()); return newRecord; } void delARecordByOrderNum(int orderNum) { int i, flag = 0; for (i = 0; i < records.size(); i++) { if (records.get(i).orderNum == orderNum) { if (!records.get(i).isDeleted) { records.get(i).isDeleted = true; } else { System.out.println("deduplication " + orderNum); } flag++; } } if (flag == 0) { System.out.println("delete error;"); } } } class Table { Order order = new Order(); int num; LocalDateTime time; long sum = 0; long origSum = 0; void add(Menu menu, String str3,String str1, String str2, int portion, int number) { //判断点菜的模式(是否存在,删除,添加) if (str2.equals("delete")) { order.delARecordByOrderNum(Integer.parseInt(str1)); } else { if (menu.searchDish(str2) != -1) { order.records.add(order.addARecord(str3,Integer.parseInt(str1), str2, portion, number, menu)); } else System.out.println(str2 + " does not exist"); } } void getSum() { double ts = time.getHour() + (double) time.getMinute() / 60; int wek = time.getDayOfWeek().getValue(); for (int i = 0; i < order.records.size(); i++) { if (!order.records.get(i).isDeleted) { origSum += order.records.get(i).getPrice(); if ((wek == 7 || wek == 6) && (ts >= 9.5) && (ts <= 21)) sum += order.records.get(i).getPrice(); if ((wek >= 1 && wek <= 5) && (ts >= 17) && (ts <= 20.5)) { if(!order.records.get(i).ds.isT) sum += Math.round(order.records.get(i).getPrice() * 0.8); else sum += Math.round(order.records.get(i).getPrice() * 0.7); } if ((wek >= 1 && wek <= 5) && (ts >= 10.5) && (ts <= 14.5)) { if(!order.records.get(i).ds.isT) sum += Math.round(order.records.get(i).getPrice() * 0.6); else sum += Math.round(order.records.get(i).getPrice() * 0.7); } } } } boolean isOpen() { //判断是否开门 int weekday = time.getDayOfWeek().getValue(); if (weekday > 0 && weekday < 6) { if (time.getHour() >= 17 && time.getHour() < 20) return true; if (time.getHour() == 20) { if (time.getMinute() <= 30) return true; } if (time.getHour() > 10 && time.getHour() < 14) return true; if (time.getHour() == 10) { if (time.getMinute() >= 30) return true; } if (time.getHour() == 14) { return time.getMinute() <= 30; } } else { if (time.getHour() > 9 && time.getHour() < 21) return true; if (time.getHour() == 9) { if (time.getMinute() >= 30) return true; } if (time.getHour() == 21) { return time.getMinute() <= 30; } } return false; } }

总结
- 基本语法:要学好Java,首先需要掌握Java的基本语法,包括数据类型、变量、运算符、控制流语句、方法等。这些是编写Java程序的基础。
- 面向对象编程:Java是面向对象的语言,因此必须熟悉面向对象编程概念,例如类、对象、继承、多态、抽象类、接口等。
-
Java中进行算术运算时,有一些注意点需要特别关注:
-
数据类型:要注意使用正确的数据类型进行运算。例如,如果两个操作数都是整数,则结果也是整数。如果一个操作数是浮点数,则结果也是浮点数。
-
整数除法:当两个整数进行除法运算时,结果将被截断为整数,而不是四舍五入。因此,如果您需要精确的小数结果,请确保至少一个操作数是浮点数。
-
运算符优先级:运算符具有不同的优先级和结合性,这会影响运算顺序。使用括号可以更清晰地指定运算顺序。
-
溢出和下溢出:对于某些数据类型(如int和long),运算结果可能超过类型范围,导致溢出或下溢出错误。在进行运算之前,可以考虑检查边界情况,并采取适当的措施。
-
避免误差:在处理浮点数时,由于计算机内部表示方式的限制,结果可能存在舍入误差。为了避免这种情况,可以考虑使用BigDecimal类来进行精确的小数运算。
-
-
在Java中进行条件判断时,有一些注意点需要特别关注:
-
条件表达式:条件表达式的类型必须是boolean,即true或false。要注意使用布尔运算符(&&、||和!)来构建复杂的条件表达式。
-
if语句:if语句通过检查指定的条件来执行分支代码。else-if和else可以扩展if语句,让代码结构更加清晰。
-
switch语句:switch语句通过对一个变量的多个值进行比较来执行不同的操作。case标签应该是常量表达式,而且不能重复。
-
null检查:在Java中,null表示空引用。在使用对象引用之前,要先检查其是否为null,以避免NullPointerException错误。
-
三目运算符:三目运算符可以简化某些条件语句的书写,并使代码更加简洁。但过度使用可能会影响代码的可读性。
-
-
Java中进行循环时,有一些注意点需要特别关注:
-
循环条件:循环应该有一个明确的结束条件,以避免无限循环。
-
控制语句:循环中可以使用break和continue等控制语句来跳出或继续循环。要注意使用它们的时机和作用范围。
-
循环类型:Java提供了for、while和do-while三种不同类型的循环,根据实际情况选择最合适的循环类型。
-
嵌套循环:可以在循环内部嵌套另一个循环。要注意在嵌套循环中正确使用break和continue关键字以及优化算法复杂度。
-
减少迭代次数:尽可能地减少循环的迭代次数可以提高程序效率。例如,在循环迭代之前,可以预处理一些数据,并使用它们进行计算。
-