写的比较仓促,主要是给自己看的,注重于代码的实践而非理论的叙述
语言的表达上稍有欠缺,并且我懒得修改
我更关注数据结构模块代码的优化,使其更聚焦于算法实现本身
而不是冗杂的总和功能实现(考研需要,孩子毕竟能力有限)
Java在理论上的抽象未必容易理解,而
实践是检验真理的唯一标准
启封の章节 · 摸鱼
极光 · Java · 常用书写学习
1.注意类型自进化情况
byte/short/char--->int---->long---->float---->double
2.二进制0b 八进制0 十进制直接写 十六进制0x 开头
/*
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.printf("%d", a);
}
}
*/ //ASRC - 极光框架
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
System.out.printf("%d", a);
}
}
输入输出测试
import java.util.Scanner;
public class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();//空格捕获
String b = sc.next();//无法捕获空格
int c = sc.nextByte();
double d = sc.nextDouble();
float f = sc.nextFloat();
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(f);
}
}
数组遍历测试
import java.util.Scanner;
public class ASRC {
public static void main(String[] args) {//内层main可以小写
Scanner sc = new Scanner(System.in);//输入启动前置
int[] a = {1, 2745, 3322, 4, 5257, 6, 7};
for (int x : a)
System.out.printf("%d ",x);
}
}
第十二周
1.关于&& 与 &
A.前者被称作短路与,如果第一条件不成立会直接跳出不执行第二条件
例如:第二条件中有i++的话就不会被执行到
面向对象class:属性+方法构造方式 (内部参数+void动作)
A.构造方法:内嵌同名class,允许不返回数值,用于初始化
B.父类继承、接口调用 启章;内存销毁操作
C.修饰符作用:限定块的访问权限
char转int型(unicode)
import java.util.*;
import java.text.*;
import java.lang.*;
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char t = sc.next().charAt(0);
System.out.printf("%d", (int) t);
}
}
第十三周
子类、父类与继承
子类:在父类的基础上进行拓展,拥有父类的方法论,可以修改替代父类的方法论
父类:会传递变量和方法给子类,数据上有无继承关系需要测试
继承:extend [父类名]
另外,不是所有的变量、方法论都会被继承;看父类权限部署
子类的权限只能比父类更宽松
类 | 包 | 子类 | 所有类 | |
---|---|---|---|---|
public | 1 | 1 | 1 | 1 |
protected | 1 | 1 | 1 | |
default | 1 | 1 | ||
private | 1 |
1.子类-父类转化规则
[父类] = new [子类] 可以的,倒过来不行
2.类型探测 instanceof
返回true false;父类引用(父类=new 子类)的探测,既是子类又是父类
3.多态性
静态多态:overload重载,同名但是参数不同(类型,或参数数量)
动态多态:override覆盖,子类通过引用方式赋值给父类(动作重写?)
4.接口
interface 定义一系列(抽象的)动作
如果某个class要implement,那么他需要实现这个接口中的所有动作
让这些·动作·都不再 抽象
接口中的数据都以常量存储(并集成继承)【变相的父类继承】
祖始类:java.lang.Object
注意事项
main是独特的方法论,可以被放在任何类中
如果在类中且【直接调用】类中的方法论,对方必须是static类型
会导致不利影响;main最好独立书写
第十四周
知识概览
一、pack import
1.package xxxxx 后面的包名称或可用 . 作为分隔,体现层次性;允许超长名称
2.通过import进行引入,但是要注意
import java.lang.* 是对lang下【首层子类】进行引入,更深层次的子类需要另外imoprt
二、四大关键字 【final 终态常量】 【static 静态】 【abstract 抽象类】 【this 实例本体】
1. abstract【抽象类】
A.修饰class 或 下属的方法,因为太抽象了、所以不能给出具体的方法
B.作为父类被引用,具体方法论在子类用同名方法中加以实现(覆盖后)
依然可以保留抽象性(如果子类的实现方法依旧是抽象的话)
C.接口的属性总是抽象的,你不写也是抽象的
D.关于抽象父类
a.内部方法论似乎也是要用abstract定义
b.方法论多采用public,因为需要被子类调用并具体化实现
不会真的有小憨批部署private吧!不会吧不会吧
2.static【静态类】
A.修饰内部类?
B.ASRC测试报告:静态类似乎是与【类】捆绑的
一个类的静态变量,对于所有同类的变量单元,都可以访问并且修改
C.对静态成员的操作,必须也是静态的状态?
D.静态成员变量只能用类名访问
import java.util.*;
import java.text.*;
import java.lang.*;
class book {
static int num;
book() {
num = 0;
}
public void add() {
num++;
}
}
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
book a=new book();
book b=new book();
book c=new book();
a.add();
a.add();
b.add();
c.add();
System.out.printf("%d",book.num);
}
}
3.final【终章常量类】
A.申明时,即刻赋值,作为常量不更变,不可(被用于)修饰抽象类型
B.修饰【方法论】时 候,方法论作为父类被子类调用,子类无权修改或覆盖
C.修饰【静态成员域】,立即赋值
D.修饰【非静态成员域】,构造方法赋值,只能赋值一次
三、接口论
1 .关于【抽象类】和【接口】的区别与联系 的思考
1.抽象类
A.抽象类是针对父类无法给出具体方法的情况下使用,定义一种抽象共有的属性,等待子类引用时由子类具体实现
比如定义宠物会叫,但是每种宠物叫声是不一样的,所以printf暂时不动,等待明确子类是猫猫狗狗才知道叫声
B.对父类宠物动作引用时,会被下沉到调用具体的子类动物动作
比如定义父类宠物,子类猫猫,定义父类a=new猫猫,那么调用父类叫声的动作,实际上就下沉调用了猫叫
C.抽象类是用来继承的,抽象方法是等待被继承后重写的,不能new出实例
D.父类中可以固定一些通用方法为final,这样不会被子类覆盖
E.抽象类的本质是【父类具有的公共属性】,实践上需要由【子类调用具体化】
2.interface接口
A.满足一定的【规范】才可以【耦合】;模块之间的耦合?
Java接口:定义多个类之间共同的【行为规范】
B.视作一种特殊的抽象类,没有构造方法,不能实例化
成员域都是常量,定义时候就需要赋值,可以引用父接口
方法无具体实现,访问限制均定义为public(JDK8后可以有更多的限制权限选择)
C.示例?
D.一个类可以有多个【接口】(规范),调用接口规范的话,就要对其所有方法加以实现
多个无关的类可以实现同一个接口
比如:显卡可以启动终止,汽车也可以启动终止
E.借用接口可以实现多继承(多个接口、多个规范标准)
F.实现了对应接口的对象,可以通过接口进行访问
3.区别与联系
A.联系是二者都体现了【子类/具有接口的子类】具有的一定公共属性,都可以通过【父类/接口】来访问【子类/实现接口的子类】
B.区别是,抽象类作为父类调用只能搞一个,接口作为一种规范标准一个子类可以调用多个接口满足多个标准;接口的方法需要全部实现,抽象继承可以保留一些抽象方法不予以实现,让二级子类去实现
ASRC-接口标准创建测试
interface Base {//接口定义-基本动作
void start();//作为多个类之间的【规范】
void stop();
}
class LookCard implements Base {
public String name;
public LookCard() {
name = "苍穹之翼";
}
public void start() {
System.out.printf("长虹显卡启动!");
}
public void stop() {
System.out.printf("长虹显卡启动关闭!");
}
}
class Car implements Base {
public String name;
public Car() {
name = "黎明之翼";
}
public void start() {
System.out.printf("汽车启动!");
}
public void stop() {
System.out.printf("汽车爆胎!");
}
}
/*【变量-->成员域】 * 【非静态方法】访问【非静态变量】:a或this.a * 【非静态方法】访问【静态变量】:a或this.a或book.a(book类名) * 【静态方法】访问【静态变量】:a或book.a * 【静态方法】访问【非静态变量】:创建实例对象后通过对象访问 * 方法论的访问 和 成员域的访问 类似 * */
/* * 静态变量可以被非静态的动作修改 * 但不能被非静态的动作访问 * 比如show动作如果是static 那么只能访问外区num和本区id,不能访问 外区域的ID * 如果去除static,那就可以访问外区ID,但是要加上this.id 来表示是外区ID * 因为内区也有个叫ID的变量(一般很少这样用,不会有哪个SB内外区ID写一个变量名称) * 太SB了 * */
MD终于来作业了!作业分析报告
1.JDK: java开发工具 (java Development Kit)
JRE: java 运行环境 java Runtime Environment
JVM: java 虚拟机 java Vritual Machine
JDK包含JRE,JRE包含JVM
2. 子类重写的方法不可以拥有比父类方法更加严格的访问权限
3.类中定义了一个有参的构造方法,系统不会再提供无参的构造方法
4.Java的Object类没有父类,也称作【顶级父类】【祖始类】
5.接口的运用我们更关注方法,其成员变量将作为常数被调动,不存在【构造方法】
6.scanner next()不能捕获带有空格的字符串,nextLine可以捕获带空格的字符串
7.接口可以被 private 或 protected 修饰符修饰
8.子类视作父类的【拓展】而非【子集】
9.方法重载,方法名称相同,参数不同
10.非抽象的父类的子类也可以是抽象的
11.接口是抽象类,抽象类是不可以继承接口的、
12.接口被编译为独立的字节码文件
7-3 设计一个银行业务类
import java.util.Scanner;
class Bank {
public static String BankName;//银行名称
private String name, password;//用户名+密码
private double money;
Bank() {
BankName = "中国银行";
money = 0;
}
public void create(String t1, String t2) {
name = t1;
password = t2;
money = 0;//呜呜好穷啊
}
public static void welcome() {
System.out.printf("%s欢迎您的到来!\n", BankName);
}
public static void welcome2() {
System.out.printf("请收好您的证件和物品,欢迎您下次光临!\n");
}
public void deposit(String t, double m) {
if (t.equals(password)) {
money += m;
System.out.printf("您的余额有%.1f元。\n", money);
} else {
System.out.printf("您的密码错误!\n");
}
}
public void withdraw(String t, double m) {
if (t.equals(password) && money >= m) {
//密码正确+可以取出
money -= m;
System.out.printf("请取走钞票,您的余额还有%.1f元。\n", money);
} else if (t.equals(password) && money < m) {
System.out.printf("您的余额不足!\n");
} else {
System.out.printf("您的密码错误!\n");
}
}
}
//【主函数调动区域】
public class ASRC {//极光·科研中心
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String t1, t2;
double t3;
Bank China = new Bank();//开户啦啦啦啦啦
China.welcome();
t1 = sc.next();
t2 = sc.next();
China.create(t1, t2);
//正确密码+存钱
t1 = sc.next();
t3 = sc.nextDouble();
China.deposit(t1, t3);
//错误密码+取钱
t1 = sc.next();
t3 = sc.nextDouble();
China.withdraw(t1, t3);
//正确密码+可以取钱
t1 = sc.next();
t3 = sc.nextDouble();
China.withdraw(t1, t3);
//正确密码+不可以取钱
t1 = sc.next();
t3 = sc.nextDouble();
China.withdraw(t1, t3);
//告辞
China.welcome2();
}
}
6-2 动物自我介绍 静态动作调用
优势,调用父类animal,可以适应输入为子类的情况
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int i = s.nextInt();//先读入 小猫还是小狗🐶
Animal a = null;
if (i == 1) {//无法捕获空格的string读入
a = new Cat(s.next(), s.next(), s.next());
} else if (i == 2) {//多带上个小狗的智商
a = new Dog(s.next(), s.next(), s.nextInt());
}
TestAnimal.introduce(a);//测试函数-直接引用内部动作的,对方必须是静态
TestAnimal.action(a);
}
}
class TestAnimal {//静态调用动作
public static void introduce(Animal a) {
a.introduce();
}
public static void action(Animal a) {
a.action();
}
}//测试函数
abstract class Animal {//父类部署
public String name;
public String color;//颜色名字
public Animal(String t1, String t2) {
name = t1;//父类-双参数构造,可以用子类的super赋值
color = t2;//变量得以继承
}
public abstract void introduce();//抽象定义
public abstract void action();
}
class Cat extends Animal {
private String eyeColor;//子类调用,多定义一个颜色
public Cat(String t1, String t2, String t3) {
super(t1, t2);//super构造首发示例,name和color对应输入
eyeColor = t3;//眼睛颜色
}
public void introduce() {
System.out.printf("My name is %s, my color is %s, my eyecolor is %s\n", name, color, eyeColor);
}
public void action() {
System.out.printf("catch mouse\n");
}
}
class Dog extends Animal {
private int IQ;
public Dog(String t1, String t2, int t3) {
super(t1, t2);
//父类继承,super用于给【父类继承变量】进行赋值
//注意先后顺序
IQ = t3;
}
public void introduce() {
System.out.printf("My name is %s, my color is %s, my IQ is %d\n", name, color, IQ);
}
public void action() {
System.out.printf("catch frisbee\n");//抓飞盘
}
}
6-3 设计门票(抽象类) 多重继承
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//当天票
Ticket a = new WalkupTicket(in.nextInt());
System.out.println(a.toString());
//预定票
Ticket b = new AdvanceTicket(in.nextInt(), in.nextInt());
System.out.println(b.toString());
//学生票
Ticket c = new StudentAdvanceTicket(in.nextInt(), in.nextInt(), in.nextInt());
System.out.println(c.toString());
}
}
abstract class Ticket {
public int num;//子类需要访问,定义private会导致无法继承
public Ticket(int t1) {
num = t1;
}//门票编号部署
abstract public String toString();//show作用
//抽象父类动作不建议采用实践性,而多采用抽象性,由子类具体状态进行拓展
}
class WalkupTicket extends Ticket {
private int p;
public WalkupTicket(int t1) {
//构造方法中,对父类留下来的变量进行初始化
// super一定要在第一行
super(t1);//父类调用一定注意super,给父类变量进行赋值
p = 50;//闭着眼睛就是50
}
public String toString() {//门票编号+价格
return "Number:" + num + ",Price:" + p;
}
}
class AdvanceTicket extends Ticket {
public int t, p;
public AdvanceTicket(int t1, int t2) {
super(t1);
t = t2;
p = t > 10 ? 30 : 40;//10天之外预定的便宜
//预定时间太着急的卖得贵
}
public String toString() {
return "Number:" + num + ",Price:" + p;
}
}
class StudentAdvanceTicket extends AdvanceTicket {
private int h;//price用父类继承的
//二级继承
public StudentAdvanceTicket(int t1, int t2, int t3) {
super(t1, t2);//编号 时间 身高
h = t3;
//基础赋值任务结束
if (h > 120)//高身高的当预订票卖
p = t2 > 10 ? 20 : 30;
else//否则就是半价
p = t2 > 10 ? 10 : 15;
}
public String toString() {
return "Number:" + num + ",Price:" + p;
}
}
7-1 两点成线 结构体传递测试
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//重复n次
while (n-- != 0) {//=0跳出,先算后--
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
Point x = new Point(a, b);
Point y = new Point(c, d);
//定义两个点
Line l = new Line(x, y);
//部署到线内
System.out.printf("%s\n", l.toString());
System.out.printf("此线段的长度为:%.1f\n", l.getLength());
}
}
}
class Point {
private int x, y;// x,y为点的坐标
//双参数构造
Point(int t1, int t2) {//双参数初始化
x = t1;
y = t2;
}
//两点距
public double distance(Point p1) {
//读入结构体点,而不是零散的xy
return Math.sqrt((p1.x - x) * (p1.x - x) + (p1.y - y) * (p1.y - y));
}
//点坐标汇报
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
class Line {
Point p1, p2;
//带参数部署
Line(Point x, Point y) {
p1 = x;
p2 = y;
}
//返回长度
public double getLength() {
return p1.distance(p2);
}
//线报告
public String toString() {
return "Line [p1=" + p1 + ", p2=" + p2 + "]";
}
}
第十五周 string
学习两种 字符串 String 和String Buffer
一、基本概述
1.常量与变量
String是常量,String Buffer是变量
2.存储论
常量的意思是,存储区的内容不变;我们在实践中为什么感觉好像是可以改变的string呢
例如 String a="asd"; 后面再部署a=a+"qwe";却能够输出asdqwe
原因在于它新开了一块空间给a,存asdqwe,原来位置的asd是不变的
Srting Buffer 就没有新开位置,而是把asd的位置直接改成asdqwe
string的存储位置似乎比较特殊,是放在【直接量池】中,而非【堆栈】(class内?)
3.补充
B.堆(malloc?手动申请)栈 (自动释放?)
二、实践论 string
1.初始化、赋值、输入输出 三种创建方法,常用12
String字符串是具有自适应性的,长度会自己边
2.string 【内容相同】的比较用equals,双等号比较地址永远不相同
ASRC-极光科研中心 String综合测试程序
特别强调!string的对比用equals来实现,而非双等号
import java.util.Scanner;
class w {
String t1, t2, t3, t5;
StringBuffer t4;
Scanner sc = new Scanner(System.in);//输入前摇(效率很低,将就用)
final int N = (int) 1e5 + 7;
w() {
t1 = " 2745409660 林雅婷 ";
t2 = "525707191 苏晓辉";
t3 = "ASRC-极光科研中心 ";
}
void menu() {
System.out.printf("T1串:%s Length=%d\n", t1, t1.length());
System.out.printf("T2串:%s Length=%d\n", t2, t2.length());
System.out.printf("T3串:%s Length=%d\n\n", t3, t3.length());
System.out.printf("ASRC-极光科研部 String 测试\n");
System.out.printf("1.部署字符串t1 2.部署字符串t2 3.内容甄别(大小写、数字)\n");
System.out.printf("4.大小写转换 5.倒置 6.子串捕获\n");
System.out.printf("7.子串位置追踪 8.去除字符串首尾多余的空格\n");
System.out.printf("9.区域插入 10.区域删除 11.字符串比较\n");
System.out.printf("12.开头匹配测试 13.结尾匹配测试 14.斩首去尾\n");
System.out.printf("15.String转char 16.t1中单字符修改\n");
System.out.printf("17-关键字拆分(:;)与 String集体转int\n");
System.out.printf("输入您的选择:");
}
void action(int t) {
switch (t) {
case 1: {
System.out.printf("输入T1字符串:");
String tmp = sc.nextLine();//挡住回车
//tmp = sc.nextLine();//再读入一次,可以加空格
t1 = tmp;
break;
}
case 2: {
System.out.printf("输入T2字符串:");
String tmp = sc.nextLine();//挡住回车
//tmp = sc.nextLine();//再读入一次,可以加空格
t3 = tmp;
break;
}
case 3: {
System.out.printf("T1字符串中,查询哪个字母呢:");
int tmp = sc.nextInt();
char tmp2 = t1.charAt(tmp);
boolean tmp3;
tmp3 = Character.isLowerCase(tmp2);
System.out.printf("字符:%c 是否小写:" + tmp3 + "\n", tmp2);
tmp3 = Character.isUpperCase(tmp2);
System.out.printf("字符:%c 是否大写:" + tmp3 + "\n", tmp2);
tmp3 = Character.isDigit(tmp2);
System.out.printf("字符:%c 是否数字:" + tmp3 + "\n", tmp2);
break;
}
case 4: {
System.out.printf("0-转化大写 else-转化小写,请输入:");
int tmp1 = sc.nextInt();
t1 = tmp1 == 0 ? t1.toUpperCase() : t1.toLowerCase();
break;
}
case 5: {
StringBuffer tmp1 = new StringBuffer(t1);//Sting内容复制给buffer
tmp1.reverse();//buffer颠倒一下
t1 = tmp1.toString();//调用toString返回string,再赋值
break;
}
case 6: {
System.out.printf("输入捕获范围(左闭右开区间)[0~%d):", t1.length());
int start = sc.nextInt(), end = sc.nextInt();
System.out.printf("捕获子串:%s\n", t1.substring(start, end));//划区捕获
System.out.printf("斩首捕获测试,斩杀坐标:(0~%d)", t1.length());
start = sc.nextInt();
System.out.printf("捕获子串:%s", t1.substring(start));//斩首元素个数=s
break;
}
case 7: {
System.out.printf("输入您要追踪的子串:");
String tmp = sc.next(), str = t1;
int idx, sum = 0, py = 0;
idx = t1.indexOf(tmp);//先追踪一次
if (idx == -1)
System.out.printf("不存在这个子串!");
while (idx != -1 && !str.isEmpty()) {
System.out.printf("发现第%d个目标 位置:%d", ++sum, py + idx);
System.out.printf(" idx=%d py=%d\n", idx, py);
py += idx + 1;//记录偏移量(因为子串被砍短了)
//主要是java的递归不会写呜呜
//【bug修复报告】:
str = str.substring(idx + 1, str.length());
idx = str.indexOf(tmp);
}
break;
}
case 8: {
t1 = t1.trim();//返回string类型
break;
}
case 9: {
System.out.printf("输入插入字符串(非空格、回车):");
String ins = sc.next();
System.out.printf("输入插入位置:");
int idx = sc.nextInt();
t4 = new StringBuffer(t1);
t4.insert(idx, ins);
t1 = t4.toString();
break;
}
case 10: {
System.out.printf("输入删除[起点,终点) (0~%d) 左闭右开:", t1.length());
int form = sc.nextInt(), num = sc.nextInt();
if (form < 0 || form > t1.length() - 1 || num > t1.length() || num <= 0)
break;
t4 = new StringBuffer(t1);
t4.delete(form, num);
t1 = t4.toString();
break;
}
case 11: {
boolean x = t1.equals(t2);
if (x)
System.out.printf("相同!");
else
System.out.printf("不同!");
break;
}
case 12: {
System.out.printf("输入前端匹配串:");
t5 = sc.nextLine();
boolean pd = t1.startsWith(t5);
if (pd)
System.out.printf("前端匹配!");
else
System.out.printf("前端失序呜呜");
break;
}
case 13: {
System.out.printf("输入后端匹配串:");
t5 = sc.nextLine();
boolean pd = t1.endsWith(t5);
if (pd)
System.out.printf("后端匹配!");
else
System.out.printf("后端失序呜呜");
break;
}
case 14: {
System.out.printf("0-斩首 else-去尾:");
int tx = sc.nextInt();
if (tx == 0) {
System.out.printf("输入斩首数量(%d以内):", t1.length());
tx = sc.nextInt();
//因为是开区间,所以del位置刚好是【1+位置】 而非存储【0+位置】
t4 = new StringBuffer(t1);
t4.delete(0, tx);
} else {
System.out.printf("输入断尾数量(%d以内):", t1.length());
//因为因为是开区间,所以要多-1
//[7,8)等于没有
tx = sc.nextInt();
t4 = new StringBuffer(t1);
t4.delete(t1.length() - tx, t1.length());
}
t1 = t4.toString();
break;
}
case 15: {
char[] ar = t1.toCharArray();
System.out.printf("生成char数组 length=%d\n", ar.length);
for (char i : ar)//注意!所有书写中只有数组的length是不用加括号的
System.out.printf("%c", i);
break;
}
case 16: {
System.out.printf("输入修改的字符:");
char tmp = sc.next().charAt(0);//单一字符读入测试
System.out.printf("输入修改的位置:");
int idx = sc.nextInt();
StringBuffer tmp2 = new StringBuffer(t1);
tmp2.setCharAt(idx, tmp);
t1 = tmp2.toString();
break;
}
case 17: {
String tmp = "Java程序设计:34 ;Web程序设计: 56;JSP程序设计:20";
String[] book = tmp.split(";");//根据封号进行拆分(不纳入封号)
int sum = 0;
for (int i = 0; i < book.length; i++) {
String[] alon = book[i].split(":");//拆分
StringBuffer cc = new StringBuffer(alon[1].trim());//去除空格
String dd = cc.toString();
int price = Integer.parseInt(dd);
System.out.printf("%s--%d\n", alon[0], price);
sum += price;
}
System.out.printf("书籍总价:%d", sum);
break;
}
case 5257: {
String tt = sc.nextLine();
t3 = tt;
}
}
System.out.println("\n\n\n");
}
}
public class ASRC {//ASRC-极光科研中心 String功能测试
public static void main(String[] args) {//主函数
Scanner sc = new Scanner(System.in);//输入前摇(效率很低,将就用)
w a = new w();
int act = 1;
while (act != 2745) {
a.menu();
act = sc.nextInt();
a.action(act);
}
}
}
四、数组 int string
1.声明与初始化
int[] a={xxx};自适应空间 int[] a=new[N];预定义空间
2.int的排序(Arrys工具包)
受到比较大的限制,要求collections和Integer格式才可以从大到小排序
元素查找也受到比较大的限制
3.实践论
极光-Arrays Sort + 逆序测试 + 静态方法测试
这里要注意,静态函数对数组的操作是可以传导回去的,常规变量不会传导回去
比如你引入一个idx在第一行(中),你赋值idx=233;回到主函数后你的idx还是0
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.Arrays;
public class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int N = 20, n = 10;
int[] a = new int[N];
//18 -6 12 27 9 31 -20 42 33 75
{
System.out.printf("size=%d\n", a.length);
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
Arrays.sort(a, 0, 10);
show(a);
reverse(a, n);
show(a);
}
}
//静态方法库,搭载在main平级位置,可以实现类似于函数的效果
public static void reverse(int[] a, int n) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int t = a[l];
a[l] = a[r];
a[r] = t;
}
}
public static void show(int[] a) {
for (int i : a)
System.out.printf("%d ", i);
System.out.printf("\n");
}
}
7-10 新子串提取示例
import java.util.Scanner;
public class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.next();
String des = sc.next();
int find = line.indexOf(des);
int res = 0;
while (find != -1) {
res++;
line = line.substring(find + des.length());
//前方无关串 到 asd 全部砍掉
find = line.indexOf(des);
System.out.printf("\n%s %d\n", line, find);
String tt = sc.next();
}
System.out.printf("%d", res);
}
}
第十六周 -容器类
ASRC-Vector
import java.util.Scanner;
import java.util.Vector;
public class ASRC {
public static void main(String[] lyt) {
Scanner sc = new Scanner(System.in);
Vector<Integer> a = new Vector<Integer>();
//增删改查测试,初始化没写容量就是10
int t = 0;
while (t != 2745) {
show(a);
t = menu();
work(t, a);
}
}
public static void show(Vector<Integer> a) {
System.out.printf("元素总数=%d 空容器:" + a.isEmpty() + "\n自适应遍历:", a.size());
for (Integer i : a)
System.out.printf("%d ", i);
System.out.printf("\n函数遍历呐:");
for (int i = 0; i < a.size(); i++)
System.out.printf("%d ", a.get(i));
System.out.printf("\n");
if (!a.isEmpty())
System.out.printf("首发元素:%d 末尾元素:%d\n", a.firstElement(), a.lastElement());
}
public static int menu() {
Scanner sc = new Scanner(System.in);
System.out.printf("1-增加元素 2-查找元素 3-修改元素\n");
System.out.printf("4-删除元素 5-元素存在询问 6-下标访问\n");
System.out.printf("输入您的选择:");
return sc.nextInt();
}
public static void work(int t, Vector<Integer> a) {
Scanner sc = new Scanner(System.in);
switch (t) {
case 1: {
int n;
System.out.printf("增加几个元素:");
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int tmp = sc.nextInt();
a.add(tmp);
}
break;
}
case 2: {
System.out.printf("输入您想查询的元素:");
int idx = sc.nextInt();
int find = a.indexOf(idx);
do {
boolean y = find == -1 ? false : true;
System.out.printf("find = %d,存在性:" + y + "\n", find);
find = a.indexOf(idx, find + 1);//继续找下一个存在idx的元素
} while (find != -1);
break;
}
case 3: {
System.out.printf("1-追踪修改 2-下标修改\n您决定:");
int mod = sc.nextInt();
if (mod == 2) {
System.out.printf("下标(%d~%d)+修改值", 0, a.size());
int idx = sc.nextInt();
a.set(idx, sc.nextInt());//设置,其实就是修改
//把idx位置修改为nextInt
} else if (mod == 1) {
System.out.printf("1-首发修改 2-全员修改\n您决定:");
int cmod = sc.nextInt();
System.out.printf("a修改为b:");
int des = sc.nextInt(), num = sc.nextInt();
if (cmod == 1)
a.set(a.indexOf(des), num);
else if (cmod == 2) {
int find = 0;
while (find != -1) {
find = a.indexOf(des);
if (find == -1)
break;
a.set(find, num);
find = a.indexOf(des, find + 1);//从下个地址开始找
}
}
break;
}
}
case 4: {
System.out.printf("1-斩首 2-去尾 3-划区删除\n您决议:");
int mod = sc.nextInt();
int l, r;
l = sc.nextInt();
if (mod == 1) {
for (int i = 0; i < l; i++)
a.remove(0);//斩首l次
} else if (mod == 2) {
for (int i = 0; i < l; i++)
a.remove(a.size() - 1);//去尾部l次
} else if (mod == 3) {
r = sc.nextInt();
for (int i = l; i <= r; i++)
a.remove(l);
}
break;
}
case 5: {
int tmp = sc.nextInt();
System.out.printf("元素存在:" + a.contains(tmp) + "\n");
break;
}
case 6: {
System.out.printf("输入下标:");
int c = a.get(sc.nextInt());
System.out.printf("对应元素:%d\n", c);
break;
}
}
System.out.printf("\n\n\n");
}
}
ASRC-Hash
import java.util.*;
import java.lang.Math;
import java.util.Vector;
class ASRC {
public static void main(String[] lyt) {
Scanner sc = new Scanner(System.in);
int t = 0;
Hashtable<String, Integer> a = new Hashtable<String, Integer>();
while (t != 2745) {
show(a);
work(t = menu(), a);
}
}
public static void show(Hashtable<String, Integer> a) {
System.out.printf("当前大小:%d 是否空哈希:" + a.isEmpty() + "\n", a.size());
Enumeration<String> x = a.keys();
while (x.hasMoreElements()) {
String key = x.nextElement();
int value = a.get(key);
System.out.printf("%s -- %d\n", key, value);
}
}
public static int menu() {
Scanner sc = new Scanner(System.in);
System.out.printf("1-新建映射(覆盖性) 2-删除映射 3-修改映射\n");
System.out.printf("4-映射增值测试 5-查找映射 \n");
System.out.printf("您决议:");
return sc.nextInt();
}
public static void work(int t, Hashtable<String, Integer> a) {
Scanner sc = new Scanner(System.in);
switch (t) {
case 1: {
System.out.printf("新建几个映射:");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.printf("%d:", i);
String t1 = sc.next();
int t2 = sc.nextInt();
a.put(t1, t2);
}
break;
}
case 2: {
System.out.printf("删除key:");
String key = sc.next();
a.remove(key);
break;
}
case 3: {
System.out.printf("输入需要修改的映射:");
String key = sc.next();
if (!a.containsKey(key)) {
System.out.printf("不存在!");
break;
}
System.out.printf("value修改为:");
a.put(key, sc.nextInt());
break;
}
case 4: {
System.out.printf("输入需要增值的映射:");
String key = sc.next();
if (!a.containsKey(key)) {
System.out.printf("不存在!");
break;
}
a.put(key, a.get(key) + sc.nextInt());
break;
}
case 5: {
System.out.printf("请输入您要查找的key:");
String key = sc.next();
if (!a.containsKey(key)) {
System.out.printf("不存在!\n");
break;
}
System.out.printf("key:%s value:%d\n", key, a.get(key));
break;
}
case 5257: {
a.clear();
break;
}
}
System.out.printf("\n\n\n");
}
}
7-13 学术会议地点统计问题 先进型·第二代
import java.util.*;
import java.text.*;
import java.lang.*;
import java.io.*;
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//【输入+斩首模块】
String inf1 = sc.nextLine(), inf2 = sc.nextLine();
char tmp = inf1.charAt(0);//看一下首发字母
String inf3 = inf1.substring(2), inf4 = inf2.substring(2);
//【数据结构模块】
final int N = 27454;
String[] inf5 = inf3.split(","), inf6 = inf4.split(",");//存拆分的信息
String[] pz = new String[N], pw = new String[N];//存去过的地方
int[] z = new int[N], w = new int[N];//存去了几次
int idxz = 0, idxw = 0;//指针
//【数据分配模块】
idxz = get_in(inf5, pz, z, idxz);//假设,首发为【张老师】
idxw = get_in(inf6, pw, w, idxw);
//此时idx恰好代表去过几个地方(遍历从0扫描<idx)
//【追踪输出模块】
boolean same = false;//默认没去过相同的地方
boolean first = true;//是否为首发输出(首发输出不要前置,)
String name1 = tmp == 'z' ? "z" : "w";//确定老师名称
String name2 = tmp != 'z' ? "z" : "w";
for (int i = 0; i < idxz; i++) {//扫描张老师
for (int j = 0; j < idxw; j++) {//扫描王老师
//我们假想先来张老师,最后输出的时候以name为准
if (pz[i].equals(pw[j])) {//【去过相同的地点】
same = true;
//【参数捕获】
boolean who = z[i] > w[j] ? true : false;//哪个老师呆的时间久
String place = who ? pz[i] : pw[j];//把他的【地点名称】拿出来
int time = max(z[i], w[j]);//【存活时间】
String tea = who ? name1 : name2;//【老师名称】
System.out.printf("%s%s:", first ? "" : ",", tea);//非首发输出需要输出逗号
System.out.printf("%s %d", place, time);
first = false;//这俩变量都是一次性使用的
}
}
}
if (!same)//确实没去过
System.out.printf("none");
}
public static int get_in(String[] inf, String[] pla, int[] num, int idx) {
for (String i : inf) {//扫描【信息流】中所有去过的地方
String[] t = i.split(" ");//啥地方
int d = Integer.parseInt(t[1]);//去了几天
boolean find = false;//是否已经存在
for (int j = 0; j < idx; j++)
if (pla[j].equals(t[0])) {//如果存在
find = true;//标记找到
//System.out.printf("找到去过:%s\n",i);
num[j] += d;//num、++
}
if (!find) {//还没找到
pla[idx] = t[0];//地点名称部署
num[idx] += d;//驻扎时间提升
idx++;
}
}
return idx;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
}
(Split+hash 第一代,屎山代码且懒得改 太恶臭了)
import java.util.Hashtable;
import java.util.Scanner;
import java.lang.Math;
import java.util.*;
import java.util.Vector;
class Main {
public static void main(String[] lyt) {
Scanner sc = new Scanner(System.in);
boolean teacher;
//哈希,存储 王老师,张老师去的地方
Hashtable<String, Integer> W = new Hashtable<String, Integer>();
Hashtable<String, Integer> Z = new Hashtable<String, Integer>();
//读入 两串信息
String information1 = sc.nextLine();
String information2 = sc.nextLine();
//看一下老师叫什么名字
char i1 = information1.charAt(0);
teacher = i1 == 'z' ? true : false;
//System.out.printf("%c %c\n", i1, i2);
//分配数据下去
String lineZ = i1 == 'z' ? information1 : information2;
String lineW = i1 != 'z' ? information1 : information2;
//斩首工作
lineW = CutHead(lineW);
lineZ = CutHead(lineZ);
//System.out.printf("\n斩首测试\n%s\n%s\n\n", lineZ, lineW);
//结点数据分离测试
String[] nodeZ = lineZ.split(","), nodeW = lineW.split(",");
/* System.out.printf("单一结点数据分离测试\n 张老师旅行数据\n");
for (String i : nodeZ)
System.out.printf("%s\n", i);
System.out.printf(" 王老师旅行数据\n");
for (String i : nodeW)
System.out.printf("%s\n", i);
*/
//哈希表部署
String test = "bj";
//System.out.printf("张老师旅行数据-提取\n");
for (String i : nodeZ) {
String[] t = i.split(" ");//结点数据分离,分离出 地名+天数
String place = t[0];
int day = Integer.parseInt(t[1]);
//System.out.printf("目的地:%s 旅行天数:%d\n", place, day);
//添加进入张老师的哈希表
if (!Z.containsKey(place))//不存在元素,新建
Z.put(place, day);
else//存在元素,叠加
Z.put(place, day + Z.get(place));//原来的天数加上去后放进去
}
//System.out.printf("张老师哈希表长度:%d\n捕获测试:%s %d\n", Z.size(), test, Z.get(test));
//System.out.printf("王老师旅行数据-提取\n");
for (String i : nodeW) {
String[] t = i.split(" ");//结点数据分离,分离出 地名+天数
String place = t[0];
int day = Integer.parseInt(t[1]);
//System.out.printf("目的地:%s 旅行天数:%d\n", place, day);
//添加进入王老师的哈希表
if (!W.containsKey(place))//不存在元素,新建
W.put(place, day);
else//存在元素,叠加
W.put(place, day + W.get(place));//原来的天数加上去后放进去
}
//System.out.printf("王老师哈希表长度:%d\n捕获测试:%s %d\n", W.size(), test, W.get(test));
//遍历张老师去过的每个地方,对比王老师,如果都去过,输出
//information1作为判断起点,以inf1为顺序
boolean findsame = false;
if (teacher) {//如果首发是张老师
boolean first = true;//是否首发输出,控制不输出前置逗号
for (String i : nodeZ) {//张老师在T1位置的情况
String[] t = i.split(" ");
String placeZ = t[0];
int dayZ = Z.get(placeZ);
//得出张老师去过的地方,现在遍历一下王老师去过的地方
String placeW;
int dayW;
Enumeration<String> y = W.keys();
while (y.hasMoreElements()) {
placeW = y.nextElement();
if (placeW.equals(placeZ)) {//发现去过相同的地方
dayW = W.get(placeW);//得出居住天数
String maxP, who;
int maxD;
if (dayW > dayZ) {//得出居住时间最长的人
if (dayW == -1 || dayZ == -1)
break;
maxD = dayW;
maxP = placeW;//王老师居住的时间长
who = "w";
} else {
if (dayW == -1 || dayZ == -1)
break;
maxD = dayZ;
maxP = placeZ;//张老师居住的时间长
who = "z";
}
if (first) { //首发输
System.out.printf("%s:%s %d", who, maxP, maxD);
first = false;
} else //非首发输出
System.out.printf(",%s:%s %d", who, maxP, maxD);
//placeZ位置对应天数改成-1,避免重复检索
Z.put(placeZ, -1);
W.put(placeZ, -1);
findsame = true;
break;
}
}
}
} else {//如果首发是张老师
boolean first = true;//是否首发输出,控制不输出前置逗号
for (String i : nodeW) {//王老师在T1位置的情况
String[] t = i.split(" ");
String placeW = t[0];
int dayW = W.get(placeW);
//得出张老师去过的地方,现在遍历一下王老师去过的地方
String placeZ;
int dayZ;
Enumeration<String> y = Z.keys();//扫描张老师去过的所有地方
while (y.hasMoreElements()) {
placeZ = y.nextElement();
if (placeW.equals(placeZ)) {//发现去过相同的地方
dayZ = Z.get(placeW);//得出居住天数
String maxP, who;
int maxD;
if (dayW > dayZ) {//得出居住时间最长的人
if (dayW == -1 || dayZ == -1)
break;
maxD = dayW;
maxP = placeW;//王老师居住的时间长
who = "w";
} else {
if (dayW == -1 || dayZ == -1)
break;
maxD = dayZ;
maxP = placeZ;//张老师居住的时间长
who = "z";
}
if (first) { //首发输
System.out.printf("%s:%s %d", who, maxP, maxD);
first = false;
} else //非首发输出
System.out.printf(",%s:%s %d", who, maxP, maxD);
//placeZ位置对应天数改成-1,避免重复检索
Z.put(placeZ, -1);
W.put(placeZ, -1);
findsame = true;
break;
}
}
}
}
if (!findsame)
System.out.printf("none");
}
public static String CutHead(String t) {
StringBuffer T = new StringBuffer(t);
T.delete(0, 2);//左闭右开,前2元素斩杀掉
return T.toString();
}
}
第十六周阶段测试总结与反思
一、查缺补漏
1.String 对象存储字符串的效率比 StringBuilder低,因为更新的时候总是要新申请空间
2.append()后部接入,对string是不适用的
3.Integer 超过127之后就会false,原因未知
Integer i=1000,j=1000;
System.out.print(i==j);
输出结果为false
4.接口论
A.里面定义【全局常量】和【公共的抽象方法】。不包含普通的变量和方法
B.默认是public+abstract,你就算不写他也会隐藏的给加上
C.接口中的方法只能用public修饰,其他的修饰符不行(除了abstract)
5.合法的标识符
英文数字下划线,首发不能是数字,符号受限,可以使用中文
下列(B)是合法标识符。
A.rwkj@163 B.Java程序设计
C.8a D.e-mail
6.完全封装类
A.私有变量没问题 B.方法不能私有,私有别人访问不了GG
C.如果是private那是对的,但是非private变量也可以通过Tom.name访问
‘提供的方法’主要是set和get,可以自己设定或者自动生成
另外,get set是惯用的方法,如果定义其他名字也是可以的
D.改变‘类设计’,是相当于改‘函数’,这样不用在每个方法调动时候,在各个地方进行调整
只需要在 类方法(相当于函数)的地方进行调整即可
二、实例题型
2.填空2-动物
两个错误的填空,分析报告
A.主类型Main要改成SimulateTest(审题)
B.getName(); 复制了一个;
接口类-测试
import java.util.Scanner;
import java.util.Vector;
import java.lang.Math;
import java.util.Collection;
import java.util.Collections;
import java.util.Arrays;
interface Animal {
void cry();
String getName();
}
class Dog implements Animal {
private String name;
Dog(String name) {
this.name = name;
}
@Override
public void cry() {
System.out.println("汪汪");
}
@Override
public String getName() {
return "我的名字叫" + name;
}
}
public class Main{// 极光·科研中心
public static void main(String[] ASRC) {
// Scanner sc = new Scanner(System.in);
Animal dog = new Dog("戴立扬");
System.out.println(dog.getName());
dog.cry();
}
}
巧喑姐姐真的好可爱呜呜
第十七周 异常
一、简述
1.抛出-捕获 机制
遇到异常则抛出,如果被捕获,用捕获方法处理
可以自定义异常类型(比如ATM取钱之余额不足)
或可交由父类处理
2.头文件示例
java.io.IOException、java.io.FileNotFoundException、 java.lang.ArrayIndexOutOfBoundsException、java.lang.NullPointerException
3.常见五大类型,异常结构概览
A.try catch 最常用的类型
B.finally 终章执行令
C.throws 消极处理(丢给父类异常)
E.throw 自定义异常(主动抛出)
注意!
1 .try后紧跟着catch,可以添加唯一的finally
2. finally无论是否return都会得到执行
3.可以无catch有finally
4.P280异常的继承
5.多个catch中,父类()要往后放,子类往前放
6.一个catch只能捕获1个异常,如果用 | 连接捕获多异常,会带一个隐性的final修饰
7.由于finally的终末执行特性,常被用于空间回收
8.finally中添加return语句会使try中的return失效
9.消极抛出throws时,子类抛出的异常不能超过父类定义,只能是子类或相同
10.throw抛出
4.常用函数
getMessage(); printf StackTrace; toString
5.ASRC-简单实践
import java.util.Scanner;
class ASRC {
public static void main(String[] ASRC) {
Scanner sc = new Scanner(System.in);
try {
while (true) {
String[] tt = new String[2];
tt[0] = sc.next();
tt[1] = sc.next();
int a = Integer.parseInt(tt[0]);
int b = Integer.parseInt(tt[1]);
int c = a / b;
}
} catch (IndexOutOfBoundsException e) {
System.out.printf("数组越界");
} catch (NumberFormatException e) {
System.out.printf("数字格式化异常,只能接受整数");
} catch (ArithmeticException e) {
System.out.printf("算数异常");
} catch (Exception e) {
System.out.printf("未知异常");
}
}
}
ASRC-极光科研部 ATM系统模拟(仅储蓄卡)
ASRC Java ATM取款机 测试https://blog.csdn.net/qq_21893163/article/details/125386100
//【头文件】
import java.util.Scanner;
import java.lang.Math;
//【结构体模块】 其实本来还想搞个花呗卡的,下次一定
abstract class Card {//父类常规卡
String Name;//开户人姓名
String ID;//卡号
String pas;//密码
String qus;//密保
String ans;//密保回答
double mon;//余额
boolean sex;//性别
Card() {
}
Card(String Name, String ID, String pas, String qus, String ans, boolean sex) {
this.Name = Name;
this.ID = ID;
this.pas = pas;
this.qus = qus;
this.ans = ans;
this.sex = sex;
}
public final void save(double t) {
mon += t;
System.out.printf("成功存款:%.2f元,当前余额:%.2f元\n\n", t, mon);
}
abstract void show();
abstract void gets(double t) throws noMoney;//取钱会出现错误
}//父类:卡类型
class sCard extends Card {
String type;
public sCard() {
super();
type = "储蓄卡";
mon = -1;
}
public sCard(String Name, String ID, String pas, String qus, String ans, boolean sex) {
super(Name, ID, pas, qus, ans, sex);//开户
type = "储蓄卡";
}
public void gets(double t) throws noMoney {
if (t > mon)
throw new noMoney();
else
mon -= t;
yy();
}//取钱,需要异常处理
public void show() {
System.out.printf("\n\n早上好!%s" + (sex ? "先生" : "女士"), Name);
System.out.printf(" 您的%s(%s) 余额:%.2f\n", type, ID, mon);
//true男士,false女士
}//基本卡面信息
public void yy() {
System.out.printf("当前余额:%.2f\n\n", mon);
}//显示余额
}//子类:储蓄卡
//【异常处理模块】
class noMoney extends Exception {
void why() {
System.out.printf("你太穷了哈哈哈哈(余额不足)!\n\n");
}
}//余额不足异常
class exit extends Exception {
void why() {
System.out.printf("当前账户已存在,不可再申请\n\n");
}
}//账户已经存在异常
class selExt extends Exception {
void why() {
System.out.printf("您的选择有误,重新输入!\n\n");
}
}//sel选择溢出
class wID extends Exception {
void why() {
System.out.printf("查无此ID!\n\n");
}
}//登陆ID异常
class wPA extends Exception {
void why() {
System.out.printf("登陆密码错误!\n\n");
}
}//登录密码错误
class wQU extends Exception {
void why() {
System.out.printf("密保回答错误!\n\n");
}
}
//【Main调动区】
class ASRC {//极光-科研中心
public static void main(String[] ASRC) {
Scanner sc = new Scanner(System.in);
int sel = 0;
sCard SXH = new sCard();//苏晓辉储蓄卡
while (sel != 4) {
menu(); //【操作界面1号-基础区域】
sel = sc.nextInt();
try {
switch (sel) {
case 1: {
if (SXH.mon != -1)
throw new exit();//抛出账户存在的异常
String name, id, pas, qus, ans;
System.out.printf("开户人姓名:");
name = sc.next();
System.out.printf("登录卡号:");
id = sc.next();
System.out.printf("账户密码:");
pas = sc.next();
System.out.printf("密保问题:");
qus = sc.next();
System.out.printf("密保答案:");
ans = sc.next();
boolean sex = true;
String sexx;
do {
System.out.printf("性别:");
sexx = sc.next();
if (sexx.equals("男"))
sex = true;
else if (sexx.equals("女"))
sex = false;
else
System.out.printf("性别输入有误,请重新输入!\n");
} while (!sexx.equals("男") && !sexx.equals("女"));
SXH = new sCard(name, id, pas, qus, ans, sex);
break;
}//开户
case 2: {
{
System.out.printf("账户ID:");
String id = sc.next();
if (!id.equals(SXH.ID))//ID异常处理
throw new wID();
System.out.printf("登陆密码:");
String pa = sc.next();
if (!pa.equals(SXH.pas))//密码异常处理
throw new wPA();
SXH.show();
}//登录模块
int idx = 2745;
while (idx != 4) {//登录成功【操作界面2号-登录区】
menu2(SXH);
idx = sc.nextInt();
try {
switch (idx) {
case 1: {
System.out.printf("存款金额:");
double t = sc.nextDouble();
SXH.save(t);
break;
}//存钱
case 2: {
System.out.printf("取款数额:");
double t = sc.nextDouble();
SXH.gets(t);
break;
}//取钱
case 3: {
SXH.yy();
break;
}//查询余额
case 4: {
System.out.printf("安全退出中.....");
break;
//啥也不干,等退出
}//退出
default: {
throw new selExt();
}//异常
}
} catch (noMoney e) {
e.why();
}//这里部署noMoney异常,就不会因为太穷被赶出银行
}
break;
}//登录
case 3: {
{
System.out.printf("%s?\n您回答:", SXH.qus);
String t = sc.next();
if (!t.equals(SXH.ans))
throw new wQU();
}//密保验证模块
int idx = 2745;
String t;
while (idx != 0) {
menu3(SXH);
idx = sc.nextInt();
try {
switch (idx) {
case 1: {
System.out.printf("修改开户人姓名为:");
SXH.Name = sc.next();
break;
}//name
case 2: {
System.out.printf("修改开户人ID为:");
SXH.ID = sc.next();
break;
}//id
case 3: {
System.out.printf("修改开户人密码为:");
SXH.pas = sc.next();
break;
}//password
case 4: {
System.out.printf("性别修改~");
SXH.sex = !SXH.sex;
break;
}//sex
case 5: {
System.out.printf("修改开户人密保为:");
SXH.qus = sc.next();
break;
}//密保
case 6: {
System.out.printf("修改密保答案为:");
SXH.ans = sc.next();
break;
}//ans
case 0: {
break;
}//退出
default: {
throw new selExt();
}
}
} catch (selExt e) {
e.why();
}
}
break;
}//修改密保
case 4: {
break;
}//退出
default: {
throw new selExt();
}//异常
}
} catch (exit e) {
e.why();
//只要创建异常实例,就会自动执行无参构造,里面不用写东西
} catch (selExt e) {
e.why();
} catch (wID e) {
e.why();
} catch (wPA e) {
e.why();
} catch (wQU e) {
e.why();
}
System.out.printf("\n\n\n");
}
}
//【静态辅助函数区域】Switch支持
public static void menu() {
System.out.printf("欢迎访问【苏晓辉银行】ATM系统\n");
System.out.printf("1-开户申请 2-登录系统\n");
System.out.printf("3-信息修改 4-退出\n");
System.out.printf("您决议:");
}
public static void menu2(sCard t) {
System.out.printf("选择您要办理的业务 当前余额:%.2f\n", t.mon);
System.out.printf("1-存钱 2-取钱 3-查询余额\n");
System.out.printf("4-安全退出\n您选择:");
}
public static void menu3(sCard t) {
System.out.printf("\n\n您已取得账户最高权限!\n");
System.out.printf("开户人姓名:%s 当前余额:%.2f\n", t.Name, t.mon);
System.out.printf("账户ID:%s\n", t.ID);
System.out.printf("密码:%s\n", t.pas);
System.out.printf("密保问题:%s\n", t.qus);
System.out.printf("密保答案:%s\n", t.ans);
System.out.printf("性别:%s\n", t.sex ? "男" : "女");
System.out.printf("您要修改的信息:\n");
System.out.printf("1-开户人姓名 2-账户ID\n");
System.out.printf("3-账户密码 4-性别\n");
System.out.printf("5-密保问题 6-密保回答\n");
System.out.printf("0-退出\n");
System.out.printf("您决议:");
}
}
PTA 十七周
5-1简单测试 自定义异常
import java.util.Scanner;
class ScoreException extends Exception {
private String message;
public ScoreException() {
message = "您输入的成绩异常,请核实!";
}
public void show() {
System.out.println(message);
}
}
class Student {
private double score;
public void setScore(double score) throws ScoreException {
if (score < 0 || score > 100)
throw new ScoreException();
else
this.score = score;
}
public double getScore() {
return this.score;
}
}
public class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student zhangsan = new Student();
try {
zhangsan.setScore(sc.nextDouble());
System.out.println("成绩为" + zhangsan.getScore());
} catch (ScoreException e) {
e.show();
} finally {
System.out.println("程序结束");
}
sc.close();
}
}
7-1 int异常输入的阻断
import java.util.Scanner;
import java.lang.NumberFormatException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws NumberFormatException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];//非数字异常示例
for (int i = 0; i < n; i++) {
try {
String t = sc.next();//先读入为string,避免错误写入int
a[i] = Integer.parseInt(t);//尝试转化为int
} catch (Exception e) {
System.out.printf("%s\n", e);
i--;//指针修正,因为这一次并没有赋值成功
}
}
System.out.printf("%s", Arrays.toString(a));
}
}
ASRC-Collection
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;
public class ASRC {
public static void main(String[] lyt) {
Scanner sc = new Scanner(System.in);
{
Collection<Object> a = new ArrayList(), b = new ArrayList();
{
a.add("林雅婷");
a.add(2.745);
a.add('s');
a.add(5257);
}//生成测试 +4
{
int t = a.contains("林雅婷") ? 1 : 0;
System.out.printf("%d ", t);
t = a.contains(2745) ? 1 : 0;
System.out.printf("%d ", t);
t = a.contains('s') ? 1 : 0;
System.out.printf("%d \n", t);
}//存在性测试
{
int t = a.contains("林雅婷") ? 1 : 0;
System.out.printf("%d ", t);
a.remove("苏晓辉");//移除不存在的元素
a.remove("林雅婷");//移除存在的元素
t = a.contains("林雅婷") ? 1 : 0;
System.out.printf("%d ", t);
}//删除测试-1
{
a.add("天琴计划");//+2 ==5
a.add("敢于斗争,敢于胜利");
System.out.printf("A.size=%d \n", a.size());
}//size
{
System.out.printf("\n集合对比测试:");
Collection t1 = new ArrayList(), t2 = new ArrayList();
t1.add("林雅婷");
t2.add("林雅婷");
int tmp = t1.equals(t2) ? 1 : 0;
System.out.printf("%d ", tmp);
t1.add("巧喑姐姐qwq");
tmp = t1.equals(t2) ? 1 : 0;
System.out.printf("%d \n", tmp);
System.out.printf("集合合并测试:");
t2.addAll(t1);//T1中所有元素拿进来
tmp = t1.contains("巧喑姐姐qwq") ? 1 : 0;
System.out.printf("%d \n", tmp);
System.out.printf("集合约束测试:");
t1.add("巧喑姐姐亲亲");
t1.add("巧喑姐姐抱抱");
t1.add("巧喑姐姐举高高");
t1.add("巧喑姐姐最可爱!");
t1.remove(t2);//把T2这个元素挖去,实际上是没有的
tmp = t1.contains("巧喑姐姐qwq") ? 1 : 0;
System.out.printf("%d ", tmp);
t1.removeAll(t2);//T2全部元素挖掉
tmp = t1.contains("巧喑姐姐qwq") ? 1 : 0;
System.out.printf("%d \n", tmp);
t1.addAll(t2);//加回来
System.out.printf("集合包含测试:");
tmp = t1.containsAll(t2) ? 1 : 0;
System.out.printf("%d ", tmp);
t2.add("巧喑姐姐睡觉觉");//添加了新的元素给T2,T1此时无法全包含T2
tmp = t1.containsAll(t2) ? 1 : 0;
System.out.printf("%d \n", tmp);
System.out.printf("集合交集选取测试:");
Collection t3 = new ArrayList(), t4 = new ArrayList();
t3.add("巧喑姐姐亲亲!");
t3.add("巧喑姐姐抱抱!");
t3.add("巧喑姐姐举高高!");
t3.add("巧喑姐姐睡觉觉!");
t3.add("巧喑姐姐摸鱼鱼!");
t4.add("巧喑姐姐亲亲!");
t4.add("巧喑姐姐抱抱!");
t4.add("巧喑姐姐陪林雅婷睡觉觉");
{
System.out.printf("\n\n遍历测试 %d\n", t3.size());
for (Object k : t3)
System.out.printf("%s\n", k);
System.out.printf("\n\n遍历测试 %d\n", t3.size());
Iterator<Object> it = t3.iterator();
while (it.hasNext())
System.out.printf("%s\n", it.next());
}
t3.retainAll(t4);//交集部分取得,其他删掉
System.out.printf("\n取得交集后,size=%d", t3.size());//只有亲亲抱抱是共有部分,其余删去
}//集合a信息测试
}
}
}
ASRC-TreeSet 具备自适应排序能力 + 迭代器输出测试 + 自适应遍历输出测试
import java.util.*;
public class ASRC {
public static void main(String[] lyt) {
Scanner sc = new Scanner(System.in);
{
TreeSet<String> a = new TreeSet<>();
a.add("巧喑姐姐亲亲!");
a.add("巧喑姐姐抱抱!");
a.add("巧喑姐姐举高高!");
a.add("巧喑姐姐睡觉觉!");
a.add("巧喑姐姐摸鱼鱼!");
a.add("巧喑姐姐亲亲!");
a.add("巧喑姐姐抱抱!");
a.add("巧喑姐姐陪林雅婷睡觉觉");
Iterator i = a.iterator();
while (i.hasNext())
System.out.printf("%s\n", i.next());
}
{
TreeSet<String> a = new TreeSet<>();
a.add("sdafawef");
a.add("waefawgfdgh");
a.add("sadfwef");
a.add("hgadfawevxscv");
a.add("bearbaer");
a.add("dtymdt");
a.add("gyrtyujr");
a.add("aqonwifb");
for (Object i : a)
System.out.printf("%s\n", i);
}
}
}
ASRC- Arraylist 容器内嵌排序
import java.util.*;
import java.lang.*;
import java.text.*;
import java.io.*;
class book implements Comparable<book>{
DateFormat mod=new SimpleDateFormat("yyyy-MM-dd");
String name;
Date time;
public book(String n,Date t) {
name=n;
time=t;
}
public int compareTo(book o) {
return o.time.compareTo(time);//最新版本往前排序
}
void show() {
System.out.printf("%s %s\n",name,mod.format(time));
}
}
class Main {
public static void main(String[] args) throws IOException, ParseException {
Scanner sc=new Scanner(System.in);//键盘读入 System.in 读入字符
DateFormat mod=new SimpleDateFormat("yyyy-MM-dd");
List<book> asd=new ArrayList<>();
String t1,t3;
Date t2;
int n=4;
for(int i=0;i<n;i++) {
t1=sc.next();//书本名称
t3=sc.next();//临时
t2=mod.parse(t3);//出版时间
asd.add(new book(t1, t2));
}
Collections.sort(asd);
for(book i:asd)
i.show();
}
}
/*
苏晓辉摸鱼大师 2021-04-27
哦哦哦嗷嗷嗷嗷 2022-03-13
胡桃大战史莱姆 2022-07-04
你是笨蛋嗷嗷嗷 2021-03-15
*/
ASRC- Arrays 非容器外置排序器
import java.util.*;
import java.lang.*;
import java.text.*;
import java.io.*;
class book{
DateFormat mod=new SimpleDateFormat("yyyy-MM-dd");
String name;
Date time;
public book(String n,Date t) {
name=n;
time=t;
}
void show() {
System.out.printf("%s %s\n",name,mod.format(time));
}
}
class c_Time implements Comparator{
public int compare(Object t1,Object t2) {
book b1=(book)t1;
book b2=(book)t2;
return b2.time.compareTo(b1.time);
}
}
class Main {
public static void main(String[] args) throws IOException, ParseException {
Scanner sc=new Scanner(System.in);//键盘读入 System.in 读入字符
DateFormat mod=new SimpleDateFormat("yyyy-MM-dd");
book[] list=new book[4];
String t1,t2;
Date t3;
int n=4;
for(int i=0;i<n;i++) {
t1=sc.next();//name
t2=sc.next();
t3=mod.parse(t2);//time
list[i]=new book(t1, t3);
}
Arrays.sort(list,new c_Time());
for(book i:list)
i.show();
}
}
/*
苏晓辉摸鱼大师 2021-04-27
哦哦哦嗷嗷嗷嗷 2022-03-13
胡桃大战史莱姆 2022-07-04
你是笨蛋嗷嗷嗷 2021-03-15
*/
ASRC-内嵌排序 Collections.sort
要点论:1.对接接口 implements Comparable<Student>
2.public int comparTo(Student t) 的书写
3.Sting 用equal,勿忘
4.ArrayList的创建
5.启动排序,Collecion.sort(a);
import java.lang.*;
import java.util.*;//内嵌排序 Collections.sort(list)
class Regiment implements Comparable<Regiment> {
int t1;
int t2;//军团建制
String name;
Regiment(int a, int b, String c) {
t1 = a;
t2 = b;
name = c;
}
public int compareTo(Regiment o) {
if (t1 != o.t1)
return t1 < o.t1 ? -1 : 1;
else if (t2 != o.t2)
return t2 < o.t2 ? -1 : 1;//让数字小的往前排
else
return 0;
}
public void show() {
System.out.printf("%s\t纵队:%d\t部门:%d\n", name, t1, t2);
}
}
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Regiment> list = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++)
list.add(new Regiment(sc.nextInt(), sc.nextInt(), sc.next()));
Collections.sort(list);
for (Regiment i : list)
i.show();
}
}
/*
10
1 5 先锋第一纵队·指挥部队
2 4 华野二纵·极光科研部
1 3 先锋第一纵队·穿插部队
2 5 华野二纵·天琴指挥部
2 1 华野二纵·攻坚英雄部队
1 4 先锋第一纵队·情报小组
2 3 华野二纵·情报与安全部门
2 2 华野二纵·发展与改革部门
1 1 先锋第一纵队·突击部队
1 2 先锋第一纵队·攻坚部队
*/
ASRC-外置排序 Arrays.sort
import java.util.*;
import java.lang.*;
//【定义 · 结构体】
class Regiment {//军团建制
int t1;//纵队
int t2;//部门
String name;
Regiment(int a, int b, String c) {
t1 = a;
t2 = b;
name = c;
}
public void show() {
System.out.printf("%s\t纵队:%d\t部门:%d\n", name, t1, t2);
}
}
//【定义 · 排序函数】
class pd1 implements Comparator {
public int compare(Object a, Object b) {
Regiment t1 = (Regiment) a;
Regiment t2 = (Regiment) b;
if (t1.t1 != t2.t1)
return t1.t1 < t2.t1 ? -1 : 1;
if (t1.t2 != t2.t2)
return t1.t2 < t2.t2 ? -1 : 1;
return 0;
}
}
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Regiment[] list = new Regiment[n];
for (int i = 0; i < n; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
String c = sc.next();
list[i] = new Regiment(a, b, c);
}
Arrays.sort(list, new pd1());
for (Regiment x : list)
x.show();
}
}
Book书籍排序测试(内嵌)
import java.util.*;
import java.lang.*;
/*
小明,2001,Java,88
小刚,2002,Java,78
小丁,2003,Java,56
小宏,2004,Java,85
小明,2001,Python,84
小刚,2002,Python,98
小丁,2003,JavaWeb,66
小宏,2004,Algorithm,87
exit
*/
class Student implements Comparable<Student> {
String Name;//姓名
String ID;//学号
double all_Score;//所有成绩
int num;//课程数量
Student(String n, String i, double s) {
num = 1;//新建一个学生
all_Score = s;
Name = n;
ID = i;
}//新建
public void add(double t) {
num++;
all_Score += t;
}//添加新课程
public double ave() {
return all_Score / num;
}//平均成绩
public int compareTo(Student t) {
if (ave() == t.ave())//成绩相同的
return ID.compareTo(t.ID);//小ID往前排(前-后=负数)
else
return (int) (t.ave() - ave());//ave-t.ave(小的往前排)
//我们这里要反过来,成绩高的往前走
}//自定义比较
}
class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Student> a = new ArrayList<>();
String t;
while (true) {
t = sc.next();
if (t.equals("exit"))
break;
String[] get = t.split(",");
//捕获一个学生
boolean find = false;//看是否是新学生
for (int i = 0; i < a.size(); i++)
if (get[1].compareTo(a.get(i).ID) == 0) {//找到了,ID相同
a.get(i).add(Integer.parseInt(get[3]));//添加新成绩即可
find = true;
break;
}
if (!find) {//没找到说明是新学生
Student newS = new Student(get[0], get[1], Integer.parseInt(get[3]));
a.add(newS);//被迫新建
}
}
//到这里说明读入完成
Collections.sort(a);
int k = 0;
for (Student i : a)
System.out.printf("No%d:%s,%s\n", ++k, i.ID, i.Name);
}
}
ASRC - 自定义类的equals重写
注意!equals内部必须使用Object类型,才算做overload
import java.util.*;
import java.lang.*;
class Computer {
String CPU;
double Main_a;
int Core;//CPU 名称 主频 内核
String Main_b;//主板型号
String name1;//内存
int size1;
String name2;//显示器
int size2;
String name3;//硬盘
int size3;
int num;
Computer(String t1, double t2, int t3, String t4, String t5, int t6, String t7, int t8, String t9, int t10, int ttt) {
CPU = t1;
Main_a = t2;
Core = t3;
Main_b = t4;
name1 = t5;
size1 = t6;
name2 = t7;
size2 = t8;
name3 = t9;
size3 = t10;
num = ttt;
}
public void show() {
System.out.printf("Computer%d:\n", num);
System.out.printf("CPU:\n");
System.out.printf("Model: %s\n", CPU);
System.out.printf("Frequency: %.1f\n", Main_a);
System.out.printf("Number of Cores: %d\n", Core);
System.out.printf("Mainboard:\n");
System.out.printf("Model: %s\n", Main_b);
System.out.printf("Memory:\n");
System.out.printf("Model: %s\n", name1);
System.out.printf("Size: %d\n", size1);
System.out.printf("Screen:\n");
System.out.printf("Model: %s\n", name2);
System.out.printf("Size: %d\n", size2);
System.out.printf("Harddisk:\n");
System.out.printf("Model: %s\n", name3);
System.out.printf("Size: %d\n", size3);
}
public boolean equals(Object t) {
if (t == null)
return false;
if (!(t instanceof Computer))
return false;
Computer k = (Computer) t;
if (!CPU.equals(k.CPU))
return false;
if (!Main_b.equals(k.Main_b))
return false;
if (!name1.equals(k.name1))
return false;
if (!name2.equals(k.name2))
return false;
if (!name3.equals(k.name3))
return false;
if (Main_a != k.Main_a)
return false;
if (Core != k.Core)
return false;
if (size1 != k.size1)
return false;
if (size2 != k.size2)
return false;
if (size3 != k.size3)
return false;
return true;
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Computer a, b;
{
String CPU = sc.next();
double Main_a = sc.nextDouble();
int Core = sc.nextInt();
String Main_b = sc.next();
String name1 = sc.next();
int size1 = sc.nextInt();
String name2 = sc.next();
int size2 = sc.nextInt();
String name3 = sc.next();
int size3 = sc.nextInt();
int ttt = 1;
a = new Computer(CPU, Main_a, Core, Main_b, name1, size1, name2, size2, name3, size3, ttt);
}
{
String CPU = sc.next();
double Main_a = sc.nextDouble();
int Core = sc.nextInt();
String Main_b = sc.next();
String name1 = sc.next();
int size1 = sc.nextInt();
String name2 = sc.next();
int size2 = sc.nextInt();
String name3 = sc.next();
int size3 = sc.nextInt();
int ttt = 2;
b = new Computer(CPU, Main_a, Core, Main_b, name1, size1, name2, size2, name3, size3, ttt);
}
System.out.printf("%s\n", a.equals(b) ? "true" : "false");
a.show();
b.show();
}
}
ASRC-Date类 简单测试
//Date类测试
import java.text.*;
import java.util.*;
import java.lang.*;
class ASRC {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
while (true) {
Date a, b;
String c1 = sc.next(), c2 = sc.next();
//格式化 年year 月month 日day 时Hour(24小时)分minute 秒second(双写)
DateFormat mod1 = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
DateFormat mod2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
a = mod1.parse(c1);//String转Date
b = mod1.parse(c2);
String c3 = mod1.format(a);//Date转String
String c4 = mod2.format(a);
int t = a.compareTo(b);//时间比较 a-b,a是未来时间时候,返回1
System.out.printf("%s\n", a);//基础输出
System.out.printf("%s\n", b);
//比较+输出
System.out.printf("比较测试:%d\n", t);//前-后(靠近未来的时间更大)
System.out.printf("格式化输出测试:\n%s\n%s\n", c3, c4);
//内容解析-解析出年月日具体信息
//时间运算-时间差 懒的搞
}
/* Date 存储 年月日 时分秒 (星期几)
不能有空格读入
2021-04-28-06:17:28
2021-04-27-16:27:01
2022-06-23-17:25:17
2023-03-13-14:17:22
2022-05-22-11:47:35
2021-07-01-09:22:40
*/
}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.lang.*;
class book implements Comparable<book> {
static int num;//书籍数量
String name;
Date pd;//发布日期
double price;
DateFormat mod = new SimpleDateFormat("yyyy-MM-dd");
book(String n, Date day, double c) {
num++;
name = n;
pd = day;
price = c;
}
public int compareTo(book o) {
return o.pd.compareTo(pd);//最新发布排在前边
}
public void show() {
System.out.printf("%s\t%s\t%.2f\n", name, mod.format(pd), price);
}
}
class ASRC {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
DateFormat mod = new SimpleDateFormat("yyyy-MM-dd");
List<book> list = new ArrayList<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String name = sc.next();
String date = sc.next();
double mon = sc.nextDouble();
Date d = mod.parse(date);
list.add(new book(name, d, mon));
}
Collections.sort(list);
System.out.printf("书籍总数=%d\n", book.num);
for (book i : list)
i.show();
}
}
/*
5
胡桃大战史莱姆 2021-11-11 15.6
母猪的产后护理 2020-07-08 14.4
刻晴的奇幻漂流 2022-08-17 18.4
凌华之逐哥出门 2020-09-21 17.8
苏晓辉的零食包 2021-04-27 27.4
*/
字符串集合求并集 TreeSet具有自适应排序功能
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class ASRC {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] s = str.split(" ");
TreeSet<String> s1 = new TreeSet<String>();
TreeSet<String> s2 = new TreeSet<String>();
int i = 0;
//取字符串放入TreeSet集合
while (s1.size() < 5)
s1.add(s[i++]);
while (s2.size() < 5)
s2.add(s[i++]);
//TreeSet会自适应排序
s1.addAll(s2);
//输出
for (Object k : s1)
System.out.printf("%s\n", k);
/*
Iterator it = s3.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}*/
}
}
实验9 sdust-Java-可实现多种排序的Book类 (外部排序函数)
import java.util.*;
import java.lang.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
class ASRC {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Book[] books = new Book[4];
//1. 从键盘接收用户输入的4本书的名称(仅有英文字符构成)、出版日期(格式:1998-10-09)、价格,生成Book对象,构造包含4本书的数组
for (int i = 0; i < 4; i++) {
String n = scan.next();
String date_str = scan.next();
Date date = null;
//将键盘录入的日期字符串转换为Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(date_str);
} catch (ParseException e) {
System.out.println("日期格式有误");
}
double p = Double.parseDouble(scan.next());
Book book = new Book(n, date, p);
books[i] = book;
}
//2.将books按照出版日期降序排序;然后输出books
Arrays.sort(books, new BookComparatorByPubDate());
for (Book book : books) {
System.out.println(book);
}
//3.将books按照价格升序排序,如果价格相同,则按照书名字母顺序排列。然后输出books
Arrays.sort(books, new BookComparatorByPrice());
for (Book book : books) {
System.out.println(book);
}
scan.close();
}
}
class Book {
public String n;
public Date d;
public double p;
public Book(String n, Date d, double p) {
this.n = n;
this.d = d;
this.p = p;
}
public String toString() {
return "书名:" + n + ",定价:" + p;
}
}
class BookComparatorByPrice implements Comparator {
public int compare(Object t1, Object t2) {
Book b1 = (Book) t1;
Book b2 = (Book) t2;
//按照价格排序,价格高的往前
//正向思考,追求价格高的在前
//那么在前的p就要比新来的大
if (b1.p == b2.p)
return b1.n.compareTo(b2.n);
else
return b1.p > b2.p ? 1 : -1;
}
}
class BookComparatorByPubDate implements Comparator {
public int compare(Object t1, Object t2) {
Book b1 = (Book) t1;
Book b2 = (Book) t2;
//正向思考,出版时间早的往前排
//前比后,r1.com(t2),会返回-1
//所以这里颠倒过来
return b2.d.compareTo(b1.d);
}
}
文件读取测试
idea中一个点,ESP是2个点,PTA也是2个点
不添加才会保存到src同级目录
ab和src文件夹同级
import java.io.*;
public class APlusB {
public static void main(String[] args) throws IOException {
File dc = new File("..//c.txt");//输出部署
if (!dc.exists())
dc.createNewFile();
FileReader a = new FileReader("..//a.txt");//字节流读取
FileReader b = new FileReader("..//b.txt");
BufferedReader ta = new BufferedReader(a);//字符流读取
BufferedReader tb = new BufferedReader(b);
String A = ta.readLine();//读取内容(字符)
String B = tb.readLine();
FileWriter wc = new FileWriter(dc.getAbsoluteFile());//得到真实地址
BufferedWriter br = new BufferedWriter(wc);//字符流写入
{
int res = (Integer.parseInt(A) + Integer.parseInt(B));
br.write("" + res);//写入字符串
}//计算与写入
{
br.close();
ta.close();
tb.close();
wc.close();
}//关闭流 模块
}
}
第十八周 输入输出
实践论-T40自测题攻坚报告
1.关于final
A.final不能修饰接口,接口中的abstract void目的就是给子类继承后重写的,final却固定了它不能被重写(父类方法)。
B.final修饰的类不能被继承【终章类型】
C.final修饰的方法不能被重载(重写)
D.final修饰的变量不能被更改(常量)
2.1个java源文件可以有1个公共类
3.泛型T
A.创建时候可以不指定类型
B.没指定就默认Object
C.基本数据类型是不可以传入泛型的(int float这些都不行)
D.java中涉及的接口、类 多数是Object(比如equals,传入Object)
4.三种注释方式
5.Java三大特征:封装 继承 多态
Java两大成员方法:类方法、实例方法
6.
char的大小写互换
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
StringBuffer sb = new StringBuffer();
String s1 = null;
for (int i = str.length() - 1; i >= 0; i--) {
char curChar = str.charAt(i);
if (curChar >= 'a' && curChar <= 'z')
s1 = String.valueOf((char) (curChar - 32));
else if (curChar >= 'A' && curChar <= 'Z')
s1 = String.valueOf((char) (curChar + 32));
else
s1 = String.valueOf(curChar);
sb.append(s1);
}
System.out.println(sb);
}
}
静态类测试-男女生人数统计
· 静态类相当于【固定的】给予某个类的变量,只要你是这个类大家都能一起用
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
Student s = new Student(sc.next(), sc.nextInt(), sc.nextInt());
}
System.out.println("number of male students:" + Student.getMaleCount());
System.out.println("number of female students:" + Student.getFemaleCount());
}
}
class Student {
static int male;
static int female;
Student(String a, int b, int c) {
male += b == 1 ? 1 : 0;
female += b == 0 ? 1 : 0;
}
static int getMaleCount() {
return male;
}
static int getFemaleCount() {
return female;
}
}
继承的优势- 6-2 图书和音像租赁
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Media[] ms = new Media[n];
for (int i = 0; i < n; i++) {
String type = sc.next();
if (type.equals("book")) {
ms[i] = new Book(sc.next(), sc.nextDouble());
} else {
ms[i] = new DVD(sc.next());
}
}
double rent = MediaShop.calculateRent(ms, sc.nextInt());
System.out.printf("%.2f", rent);
}
}
/*
5
book Earth 25.3
book Insights 34
dvd AI
dvd Transformer
book Sun 45.6
20
*/
class Media {
}
class Book extends Media {
double rent;
Book(String a, double b) {
rent = b / 100;
}
}
class DVD extends Media {
DVD(String a) {
}
}
class MediaShop {
static double calculateRent(Media[] a, int b) {
double all = 0;
for (Media i : a) {
if (i instanceof Book)
all += b * ((Book) i).rent;
else
all += b;
}
return all;
}
}
ASRC-自定义排序测试(Collections 内嵌)
注意!定义成list才可以调用collections.sort,定义collection不能调用sort
import java.util.*;
import java.lang.*;
import java.text.*;
class Book implements Comparable<Book> {
String n;//名称
Date d;//日期
int v;//版本
double p;//价格
String da;//dat展示
Book(String n, Date d, int v, double p, String da) {
this.n = n;
this.d = d;
this.v = v;
this.p = p;
this.da = da;
}
public void show() {
System.out.printf("名称:%s\n", n);
System.out.printf("日期:%s\n", da);
System.out.printf("版本:%d\n", v);
System.out.printf("价格:%.2f\n\n", p);
}
public int compareTo(Book t) {//后来接入者t
if (!n.equals(t.n))
return n.compareTo(t.n);//名称:a开头优先(string默认是,abcd字母顺序往前放)
else if (!d.equals(t.d))
return t.d.compareTo(d);//新日期优先(date默认是,旧日期往前放,这里要颠倒过来)
else if (v != t.v)
return v > t.v ? -1 : 1;//高版本优先(int,返回-1即可生成既定部署)
else if (p != t.p)
return p < t.p ? -1 : 1;//低价格优先(int,返回-1即可生成既定部署)
else
return 0;
}
}
class ASRC {//ASRC - Class自定义排序测试(内嵌)(ArrayList)(Date)
public static void main(String[] asd) throws ParseException {
Scanner sc = new Scanner(System.in);
DateFormat mod = new SimpleDateFormat("yyyy-MM-dd");
int n = sc.nextInt();
List<Book> list = new ArrayList<Book>(n);
for (int i = 0; i < n; i++) {
String na = sc.next();//名称
String da = sc.next();//日期
Date date = mod.parse(da);//String转Date
//da = mod.format(date);//Date转String
int v = sc.nextInt();//版本
double p = sc.nextDouble();//价格
list.add(new Book(na, date, v, p, da));
}
Collections.sort(list);
for (Book i : list)
i.show();
}
}
/*
11
c-胡桃大战史莱姆
2021-07-21
3
27.7
c-胡桃大战史莱姆
2021-07-18
3
27.7
c-胡桃大战史莱姆
2021-07-24
3
27.7
c-胡桃大战史莱姆
2021-08-21
3
27.7
a-胡桃大战史莱姆
2021-07-21
3
16.7
a-胡桃大战史莱姆
2021-07-21
3
27.7
a-胡桃大战史莱姆
2021-07-21
3
15.7
d-胡桃大战史莱姆
2021-07-21
2
27.7
d-胡桃大战史莱姆
2021-07-21
1
27.7
d-胡桃大战史莱姆
2021-07-21
3
27.7
b-胡桃大战史莱姆
2021-07-21
3
27.7
*/
ASRC-自定义排序测试(Arrays)(外部排序)
import java.util.*;
import java.lang.*;
import java.text.*;
class book {
String n;//书籍名称
Date d;//出版日期
double p;//价格
DateFormat mod = new SimpleDateFormat("yyyy-MM-dd");
book(String a, Date b, double c) {
n = a;
d = b;
p = c;
}
public void show() {
System.out.printf("名称:%s\n", n);
System.out.printf("日期:%s\n", mod.format(d));
System.out.printf("价格:%.2f\n\n", p);
}
}
class c_Name implements Comparator {
public int compare(Object t1, Object t2) {
book b1 = (book) t1;
book b2 = (book) t2;
return b1.n.compareTo(b2.n);
}
}
class c_Date implements Comparator {
public int compare(Object t1, Object t2) {
book b1 = (book) t1;
book b2 = (book) t2;
return b2.d.compareTo(b1.d);
}
}
class c_Price implements Comparator {
public int compare(Object t1, Object t2) {
book b1 = (book) t1;
book b2 = (book) t2;
if (b1.p == b2.p)
return 0;
return b1.p < b2.p ? -1 : 1;
}
}
class ASRC {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
DateFormat mod = new SimpleDateFormat("yyyy-MM-dd");
int n = sc.nextInt();
book[] list = new book[n];
for (int i = 0; i < n; i++) {
String name = sc.next();
String date1 = sc.next();
double price = sc.nextDouble();
Date date = mod.parse(date1);
book a = new book(name, date, price);
list[i] = a;
}
//Arrays.sort(list, new c_Date());
Arrays.sort(list, new c_Price());
//Arrays.sort(list, new c_Name());
for (book i : list)
i.show();
}
}
/*
4
c-刻晴稻妻寻夫记
2021-04-27
16.8
d-刻晴稻妻寻夫记
2021-06-15
14.8
a-刻晴稻妻寻夫记
2021-08-14
26.8
b-刻晴稻妻寻夫记
2021-01-05
6.8
*/
泛型T
输入输出
file类,不支持读取,只是访问修改文件的信息
目录、文件 都可以作为file对象
separator 自适应斜杠,提高兼容性
本章节我们要主动关闭IO流
IO类,支持读写文件
字节流 字符流
01101字节流
unicode 字符流
能用字符的地方也可以用字节流
结尾 stream 字节流
结尾 reader writer 字符流
buffer带缓存,效率更高
一个字节流不能直接转换成字符流,需要有桥梁
比如InputStream到InputStreamReader(桥梁流类)到BufferedReader
Buffer reader 可以换行读取,而且有缓存块速度更快
read 必有异常,要放在try中
System.in.read(bu); 从键盘读入【字符】到,bu里
read的 字节以int型存储
close之前必须要flush一下,告诉系统不要缓存了赶紧写进去
避免直接close导致缓存区丢失
先关闭输入,再flush再关闭输出
字符流的优势,在于可以识别回车
桥梁流类可以指定字符集,可以借此规避乱码问题
处理字符的用read writer结尾