和1与,看是否为0,判断32次

#include <stdio.h>
int main()
{
int a;
scanf("%d", &a);
int i = 0;
int count = 0;
for (i = 0; i < 32; i++) {
if (a & 1 == 1)
count++;
a = a >> 1;
}
printf("%d ", count);
return 0;
}
Scanner sc = new Scanner(System.in);
int count = 0;
int a = sc.nextInt();
for (int i = 0; i < 32; i++) {
if ((a & 1) == 1)
count++;
a >>= 1;
}
sc.close();
System.out.println("1的个数为 " + count);

//另一种写法
int n = 15
int cc = 0;
while (n != 0) {
if ((n & 1) != 0) {
cc++;
}
n >>>= 1;
}

妙妙方法

一个数字与上这个数字减一的数,该数二进制最右边的1必然会消除掉,以此类推,从右往左,每一次进行按位与操作,都会取消掉一个1,直到该数字变为0,跳出循环,就得到了该数字二进制中1的个数。
以21(0001 0011)为例:

0001 0011

0001 0010

0001 0010 第一次与的结果

0001 0001

0001 0000 第二次与的结果

0000 1111

0000 0000 第三次与的结果,跳出循环,count = 3;

#include <stdio.h>
int main()
{
int a;
scanf("%d", &a);
int i = 0;
int count = 0;
while (a != 0) {
a = a & (a - 1);
count++;
}
printf("%d ", count);
return 0;
}
int n = 15;
int ccc = 0;
while (n != 0) {
n = n & (n - 1);
ccc++;
}
System.out.println(ccc);

水仙花数

int a = 0;
int b = 0;
int c = 0;
for (int i = 100; i < 1000; i++) {
a = i % 10;
b = i / 10 % 10;
c = i / 100;
if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == i)
System.out.println(i);
}
int tmp = 0;
for (int i = 100; i < 999; i++) {
int tem1 = i;
while(tem1 != 0) {
tmp += Math.pow(tem1 % 10, 3);
tem1 /= 10;
}
if (tmp == i)
System.out.println(tmp);
tmp = 0;
}

拓展:一个整数的各个位数的位数次方

for (int i = 1; i < 999999; i++) {
int count = 0; //记录位数
int tmp = i; //保存i值,以免影响for循环
while (tmp != 0) {
tmp /= 10;
count++;
}
tmp = i;//再次用来求各个位数
int sum = 0; //保存各个位数的位数次方
while( tmp != 0 ) {
sum += Math.pow(tmp % 10, count);
tmp /= 10;
}
if (sum == i)
System.out.println(i);
}

5_30学习笔记

/**
* Created with IntelliJ IDEA
* Description
* User: yxz
* Data: 2023-05-30
* Time: 14:12
*/
import java.util.Scanner;
public class test530 {
public static void main8(String[] args) {
/* 求最大公约数 */
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int rand = a % b;
while(rand != 0) {
a = b;
b = rand;
rand = a % b;
}
System.out.println(b);
}
public static void main7(String[] args) {
/* 判断素数方法2 */
int n = 2;
int i = 2;
for (;i < Math.sqrt(n); i++) {
if (n % i == 0) {
System.out.println("不是素数");
break;
}
}
if (i > Math.sqrt(n)) {
System.out.println("是素数");
}
}
public static void main6(String[] args) {
/* 判断素数 */
int n = 7;
int i = 2;
for (; i <= n / 2; i++) {
if (n % i == 0) {
System.out.println("不是素数");
break;
}
}
if (i > n / 2) {
System.out.println("是素数");
}
}
public static void main5(String[] args) {
/* 输出整数的2进制 偶数位序列 奇数位序列 */
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 31; i >= 1; i -= 2) {
System.out.print(((a >> i) & 1) + " ");
}//偶数位
System.out.println();
for (int i = 30; i >=1; i -= 2) {
System.out.print(((a >> i) & 1) + " ");
}//奇数位
}
public static void main4(String[] args) {
/* 输入密码 */
Scanner sc = new Scanner(System.in);
int count = 3;
while (count != 0) {
System.out.println("请输入你的密码,共有" + count + "次机会!");
String pass = sc.nextLine();
if (pass.equals("123")) {
System.out.println("登陆成功");
break;
} else {
System.out.println("密码错误");
}
count--;
}
}
public static void main3(String[] args) {
/* 输出整数的每一位 */
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
while (n != 0) {
System.out.print( n % 10);
n /= 10;
}
}
}
public static void main2(String[] args) {
/* 乘法口诀表 */
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + "*" + j + "=" + i * j + " ");
}
System.out.println();
}
}
public static void main1(String[] args) {
/* X形图案 */
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((i == j) || (i + j == n - 1)) {
System.out.print('*');
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
}

方法

/**
* Created with IntelliJ IDEA
* Description
* User: yxz
* Data: 2023-05-30
* Time: 16:11
*/
public class fangfa1 {
//闰年
public static boolean isiLeapYear(int year) {
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 9)) {
return true;
} else {
return false;
}
}
//

//方法定义
//修饰符 返回值类型 方法名称([参数类型 形参]){
// 方法代码块
//[return 返回值];
// }
public static void add(int a, int b) {
System.out.println(a + b);
}
public static void main1(String[] args) {
int x = 1;
int y = 1;
int year = 2021;
//System.out.println(isiLeapYear(year));
//int ret = add(x, y);//实际参数 ret:接收方法得返回值
}
}

方法的重载与重写的区别

方法重写是存在子父类之间的,子类定义的方法与父类中的方法具有相同的方法名字,相同的参数表和相同的返回类型

方法重载是指同一个类中的多个方法具有相同的名字,但这些方法具有不同的参数列表,即参数的数量或参数类型不能完全相同

  1. 方法的名称必须一样
  2. 方法的参数不一样 [数据类型, 个数, 顺序]
  3. 返回值没有要求
  4. 签名使得同名的方法可以区别

递归

/**
* Created with IntelliJ IDEA
* Description
* User: yxz
* Data: 2023-05-30
* Time: 20:20
*/
public class digui {
/**
* 汉诺塔
* @param pos1 起始位置
* @param pos2 中转位置
* @param pos3 目标位置
* @param n
*/
public static void hanio(int n, char pos1, char pos2, char pos3) {
if (n == 1) {
move(pos1, pos3);
return;
}
hanio(n - 1, pos1, pos3, pos2);
move(pos1, pos3);
hanio(n - 1, pos2, pos1, pos3);
}

/**
*
* @param pos1 起始位置
* @param pos2 目标位置
*/
public static void move(char pos1, char pos2) {
System.out.print(pos1 + " -> " + pos2 + " ");
}
//求1 +...+n;
public static int fun2(int n) {
if (n == 1) {
return 1;
}
return n + fun2(n - 1);
}

public static void main2(String[] args) {
hanio(1, 'A', 'B', 'C');
System.out.println();
hanio(2, 'A', 'B', 'C');
System.out.println();
hanio(3, 'A', 'B', 'C');
System.out.println();
}
//求1 +...+n;
public static int fun2(int n) {
if (n == 1) {
return 1;
}
return n + fun2(n - 1);
}
//求数字的各位数之和
public static int sum(int n) {
if (n < 10) {
return n;
}
int tmp = n % 10 + sum(n / 10);
return tmp;
}
//按顺序打印数字的每一位,
public static void print(int num) {
if (num > 9) {
print(num / 10);
}
System.out.println(num % 10);
}

//阶乘
public static int fac(int n) {
if (n == 1) {
return 1;
}
int tmp = n * fac(n - 1);
return tmp;
}
public static void main3(String[] args) {
System.out.println(fac(5));
}
public static void function(int a) {
if (a == 1) {
System.out.println(a);
return;
}
function(a - 1);
System.out.println(a);
}

public static void main2(String[] args) {
function(10);
}
/**
* 求俩个整数的最大值
* @param a
* @param b
* @return
*/
public static int max2(int a, int b) {
return a > b ? a : b;
}

/**
* 求三个数的最大值
* @param a
* @param b
* @param c
* @return
*/
public static int max3(int a, int b, int c) {
int max = max2(a, b);
return max > c ? max : c;
}
//重载写法
public static int max(int a, int b, int c) {
int ret = max2(a, b);
return ret > c ? ret : c;
}
//fib
public static int fib(int n) {
int f1 = 1;
int f2 = 1;
int f3 = 1;
for (int i = 3; i <= n; i++) {
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
public static int fib1(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib1(n - 1) + fib( n - 2);
}
}
public static void main1(String[] args) {
System.out.println(fib1(1));
System.out.println(fib1(2));
System.out.println(fib1(5));
}

}

数组

数组是有一种引用数据类型

基本定义

public class Arr {

public static void main(String[] args) {
int[] arr1 = {1,2,3};
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
System.out.println();
// 数组当中数据类型定义的变量 : 数组名 ,但拿不到数组下标
for (int x: arr1) {
System.out.print(x + " ");
}
System.out.println();
//专门用来操作数组 Array 需要导入一个包
//把数组转变为字符串,然后返回
String ret = Arrays.toString(arr1);
System.out.println(ret);
}
public static void main2(String[] args) {
double arr1[] = new double[1];//0.0
float arr2[] = new float[1];//0.0f
System.out.println(arr1[0]);
System.out.println(arr2[0]);
}


public static void main1(String[] args) {
int a1 = 1;
int a2 = 2;
int a3 = 3;
int[] arr = {a1, a2, a3};
int[] arr2 = {1, 2, 3};//直接赋值
int[] arr3 = new int[]{1,2,3,4};//动态初始化
//没有本质区别,只有写法上的区别.
int[] arr4 = new int[10];//分配空间,默认值0或0.0,boolean是false
System.out.println(arr4[1]);
int len = arr3.length;
System.out.println(arr[2]);
System.out.println(len);

}

数组(引用类型和应用场景)

image.png

  • 程序计数器(PC Register):只是一个很小的空间,保存下一条执行的指令的地址

  • 虚拟机栈(JVM Stack):与方法调用相关的一些信息,每个方法在执行时,都会先创建一个栈帧,栈帧中包含有:局部变量表、操作数栈、动态链接、返回地址以及其他的一些信息,保存的都是与方法执行时相关的一些信息。比如:局部变量。当方法运行结束后,栈帧就被销毁了,即栈帧中保存的数据也被销毁了。

  • 本地方法栈(Native Method Stack):本地方法栈与虚拟机栈的作用类似.只不过保存的内容是Native方法的局部变量.在有些版本的JVM实现中(例如HotSpot),本地方法栈和虚拟机栈是一起的

  • (Heap):JVM所管理的最大内存区域.使用new 创建的对象都是在堆上保存(例如前面的 new int[](1,2,31),堆是随着程序开始运行时而创建,随着程序的退出而销毁,堆中的数据只要还有在使用,就不会被销毁。

  • 方法区(Method Area):用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等数据.方法编译出的的字节码就是保存在这个区域

现在我们只简单关心堆和虚拟机栈这两块空间,后序JVM中还会更详细介绍。

image.png

public class Arr {

public static void main7(String[] args) {
int[] arr = null;//引用对象的0值,代表这个引用不指向任何对象
//System.out.println(arr[0]);没对象,哪来的长度,空指针异常
//所以不能进行读写操作,否则抛出NullPointException
System.out.println(arr);
}
public static void main6(String[] args) {
//一个引用不能指向多个对象,但一个对象可以被多个引用指向
int[] arr = {1,2,3,4};
int[] arr2 = {3,4,5,7};
arr = arr2; //arr没了,此时没人引用{1,2,3,4}就自动回收了
System.out.println(Arrays.toString(arr));//[3, 4, 5, 7]
System.out.println(Arrays.toString(arr2));//[3, 4, 5, 7]
}
public static void main5(String[] args) {
int[] arr = {1,2,3,4};
System.out.println(Arrays.toString(arr));

int[] arr2 = arr;//arr2这个引用指向了arr引用所引用的对象
arr2[1] = 99;//改arr2 arr也会变
System.out.println(Arrays.toString(arr));//[1, 99, 3, 4]
System.out.println(Arrays.toString(arr2));//[1, 99, 3, 4]
public static void main4(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
System.out.println(Arrays.toString(arr));
}

}

数组的应用场景

public static void func1(int[] arr) {
arr = new int[10];
//System.out.println(Arrays.toString(arr));[0...0]
}
public static void func2(int[] arr) {
arr[0] = 99;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4};
func1(arr);
System.out.println(Arrays.toString(arr));//[1,2,3,4]
func2(arr);
System.out.println(Arrays.toString(arr));//[1,2,3,4]
}

image.png

// int[] arr = { 1, 2,3 ,4};//整体初始化只有一次机会!就是在定义的同时初始化;
public static void swap(int[] array) {
int tmp = array[0];
array[0] = array[1];
array[1] = tmp;
}

public static void main(String[] args) {
int[] tmp = { 1, 2};
System.out.println("交换前: " + tmp[0] + " " + tmp[1]);
swap(tmp);
System.out.println("交换后: "+ tmp[0] + " " + tmp[1]);
}
public static int[] func3() {//返回一整个数组
int[] tmp = {1,2,3,4,5,6,7,8,9};
return tmp;
}
public static void main2(String[] args) {
int[] ret = func3();
System.out.println(Arrays.toString(ret));
}

  1. 数组对象是在堆上的
  2. 引用变量目前是在main函数里面的,属于局部变量,当函数结束或就会被收回内存
  3. 是变量被回收后,对象没人引用了,自动回收了,fun函数里的地址和main函数里的地址不同,fun里的回收后,对象还在,但fun里有队arr的操作会保存下来,因为对象被改变了。

练习

数组转字符串

public static String myToString(int[] tmp) {
if (tmp == null) {
return "null";
} else {
String ret = "[";
for (int i = 0; i < tmp.length; i++) {
ret = ret + tmp[i];
if (i != tmp.length - 1) {
ret += ",";
}
}
ret = ret + "]";
return ret;
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
int[] arr2 = null;
String ret1 = myToString(array);
String ret2= myToString(arr2);
System.out.println(ret1);
System.out.println(ret2);
}

法二

public static String toString(int[] arr) {
if (arr == null)
return "null";
int iMax = arr.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0 ; ; i++) {
b.append(arr[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
int[] arr2 = null;
String ret1 = toString(array);
String ret2= toString(arr2);
System.out.println(ret1);
System.out.println(ret2);
}

数组拷贝

public static void main(String[] args) {
int[] arr = {1,3,5,7,9};
int[] arr2 = arr;//这不算拷贝,没有新的内存空间
int[] arr3 = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
arr3[i] = arr[i];
}
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr3));
}

方法实现

public static void main(String[] args) {
int[] arr = {1,2,3,4};
int[] arr2 = Arrays.copyOf(arr, arr.length);
System.out.println(Arrays.toString(arr2));
//扩容2倍
int[] arr3 = Arrays.copyOf(arr, arr.length * 2);
System.out.println(Arrays.toString(arr3));

int[] arr4 = Arrays.copyOfRange(arr, 2, 3);
System.out.println(Arrays.toString(arr4));
int[] arr5 = arr.clone();
System.out.println(Arrays.toString(arr5));
}

求平均值

public static double avg(int arr[]) {
int sum = 0;
for(int x : arr) {
sum += x;
}
return sum * 1.0 / arr.length;
}
public static void main(String[] args) {
int[] arr = {1, 2 ,3, 3};
System.out.println(avg(arr));
}

找下标

public static int find1(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
public static int binarySearch(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = (left + right) >>> 1;
if (arr[mid] < key) {
left = mid + 1;
} else if (arr[mid] > key) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 8 ,3, 3,4,5,7};
Arrays.sort(arr);//快排,升序,降序需要比较器,没学;
//也可以用Arrays.binarySearch()
System.out.println(Arrays.toString(arr));
System.out.println(binarySearch(arr, 4));
}

复习下冒泡

public static void sort(int[] arr) {
int len = arr.length - 1;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
System.out.println(Arrays.toString(arr));
}

优化

public static void bubblesort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
boolean flg = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flg =true;
}
}
if (flg == false)
return;
}
}
public static void main(String[] args) {
int[] arr = {10,3,7,8,5};
bubblesort(arr);
System.out.println(Arrays.toString(arr));
}

数组逆序

public static void reverse(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
reverse(arr);
System.out.println(Arrays.toString(arr));
}

数组比较

public static void main(String[] args) {
int[] arr = {1,2,3};
int[] arr2 = {1,2,3};
boolean fla = Arrays.equals(arr, arr2);
System.out.println(fla);
}

批量初始化

public static void main(String[] args) {
int[] arr = new int[10];
Arrays.fill(arr, 2, 5, -1);
System.out.println(Arrays.toString(arr));
}s

二维数组


public static void main3(String[] args) {
//不规则数组,没指定列arr[0]是null
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[4];
System.out.println(Arrays.toString(arr[0]));
System.out.println(Arrays.toString(arr[1]));
}
public static void main2(String[] args) {
//打印
int[][] arr = new int[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int[] arr1: arr) {
for (int x : arr1) {
System.out.print(x + " ");
}
System.out.println();
}
System.out.println();
System.out.println(Arrays.toString(arr));//地址
System.out.println(Arrays.toString(arr[0]));//一维数组
System.out.println(Arrays.toString(arr[1]));//地址
System.out.println(Arrays.deepToString(arr));//[[0, 0, 0], [0, 0, 0]]
}
//定义
public static void main1(String[] args) {
int[][] arr = new int[2][3];

int[][] arr2 = new int[][]{{1,2,3},{4,5,6}};

int[][] arr3 = {{1,3,3},{8,9,0}};
}

作业

//数组中是否存在三个连续的奇数
public static boolean func5(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i] % 2 != 0) {
count++;
if (count ==3) {
return true;
}
} else {
count = 0;
}
}
return false;
}

public static void main(String[] args) {
int[] arr = {1,2,3,5,7};
System.out.println(func5(arr));
}
//多数元素leecode169
public int majorityElement(int[] arr) {
Arrays.sort(arr);
return arr[arr.length/2];
}
//投票法
public static int majorityElement2(int[] arr) {
int ret = arr[0];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ret) {
count++;
} else {
count--;
}
if (count == 0) {
ret = arr[i + 1];
}
}
return ret;
}

public static void main(String[] args) {
int[] arr = {1,2,3,4,4};
System.out.println(majorityElement2(arr));
}
//一个数组,进有一个元素出现一次,其它都出现俩次
public static int func4(int[] arr) {
int ret = 0;
for (int i = 0; i < arr.length; i++) {
ret = ret ^ arr[i];
}
return ret;
}

public static void main5(String[] args) {
int[] arr = {1,2, 3, 2, 1};
System.out.println(func4(arr));

}
public static int[] funca(int[] arr, int target) {
int[] ret = new int[2];
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
ret[0] = i;
ret[1] = j;
return ret;
}
}
}
return ret;
}



//奇数位于偶数之前
public static void func(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
while (left < right && arr[left] % 2 != 0) {
left++;
}
while (left < right && arr[right] % 2 == 0) {
right--;
}
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}
}
public static void main5(String[] args) {
int[] arr = {1,2,3,4,5,6};
func(arr);
System.out.println(Arrays.toString(arr));
}
public static void transform1(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 2;
}
}
public static int[] transform(int[] a) {
int[] tmpArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
tmpArr[i] = a[i] * 2;
}
return tmpArr;
}

public static void main4(String[] args) {
int[] a = {1,2,3,4,6};
int[] ret = transform(a);//a不变
System.out.println(Arrays.toString(ret));
}

class Person {
//属性
public int age;
public String name;
//行为(方法)
public void eat() {
System.out.println("吃饭");
}
}
//类名 大驼峰
//方法名 小驼峰
class WashJi {
//属性[字段]---》成员属性
public String brand; //品牌
public String type; //型号
public double weight; //重量
public double length; //长度
public double width; //宽
public double height; //高
public String color; //颜色

//行为[方法]----》成员方法
public void WashJi() {
System.out.println("洗衣功能");
}
public void dryClothes() {
System.out.println("脱水功能");
}
public void setTime() {
System.out.println("定时功能");
}
}
class Dog {
public String name;
public String color;
public void barks() {
System.out.println(name + "汪汪叫~~~");
}
public void wag() {
System.out.println(name + "摇尾巴" );
}
public static void func(String ret) {
System.out.println(ret);
}
}

public class cal {
public static void main(String[] args) {
//实例化一个对象
Dog dog = new Dog();
dog.name = "ctl";
dog.barks();
dog.name="ctl1";
dog.wag();
Dog dog2 = new Dog();
dog2.name = "ximu";
dog2.wag();
String ret = "ctl1";
//通过一个类可以实例化无数对象
dog.func(ret);
}
public static void main1(String[] args) {
Person person = new Person();
person.eat();
}
}

this

  • this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
  • this只能在成员方法中使用
  • 在成员方法中,this只能引用当前对象,不能再引用其它对象
  • this是成员方法第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this来接收
public class cal {
public int year;
public int month;
public int day;
//this.day = 1会报错
public void getData(int year, int month, int day) {
year = year;
month = month;
day = day;
}//这里局部变量会被回收,局部变量优先,这里只是自己给自己赋值了
public void getData1(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printData() {
System.out.println(year + "/ " + month + "/ " + day);
}
public void printData1() {
System.out.println(this.year + "/ " + this.month + "/ " + this.day);
}

public static void main(String[] args) {
cal c1 = new cal();
cal c2 = new cal();
cal c3 = new cal();

c1.getData(1,1,1); // 0/0/0
c2.getData1(1,1,1);// 1 / 1/ 1
c3.getData1(1,1,1);

c1.printData1();
c2.printData1();
c3.printData1();

}
public static void main1(String[] args) {
cal c1 = new cal();
//c1.getData(1,1,10);
//c1.getData1(2023,6,6);
/*c1.month=2;
c1.year=1;
c1.day=3;*/
c1.printData();
}
}

作业

public class Stu {
public String name;
public int age;
public void setInof(String name, int age) {
this.name = name;
this.age = age;
}
public void myName() {
System.out.println("My name is " + name);
}
public void myInfo() {
this.myName();
System.out.println(this.age);
}


public static void main(String[] args) {
Stu stu = new Stu();
stu.setInof("yxz", 12);
stu.myName();
stu.myInfo();
}
}

构造方法

public class Stu {
public String name = "yxz";//就地初始化,但只适合默认的一些量
public int age;
public void setInof(String name, int age) {
this.name = name;
this.age = age;
}
public void myName() {
System.out.println("My name is " + name);
}
//构造方法
public Stu() {
//要写在第一条
this("yxz", 12);
System.out.println("不带参数的构造方法");
}
public Stu(String name, int age) {//构造方法可以重载1.方法名相同,2.参数列表不同3.返回值不一定相同
//this();//不能循环调用
System.out.println("带俩个参数的构造犯法");
this.name=name;
this.age=age;
}
public void myInfo() {
this.myName();
System.out.println(this.age);
}


public static void main2(String[] args) {
Stu stu = new Stu();//实例化时一定会调用构造方法,若没有提供,编译器会提供一个
Stu stu2 = new Stu("yxz", 12);//构造方法调用完成后,对象才实际上产生
//stu.setInof("yxz", 12);//引用类型默认值是null
/* stu.myName();
stu.myInfo();*/
}
}

封装

class Person {
public String name;
public int age;
private String add;

public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void show() {
System.out.println("姓名:" + name + "\n" + " 年龄:" + age);
}

}

public class Test2 {
public int age;
public static void main1(String[] args) {
Person pe = new Person();
pe.setName("yxz");

}
}

private

class Alpha {
private int iamprivate;

public Alpha( int i){
iamprivate=i;
}

boolean isEqualTo(Alpha anotherAlpha) {
if (this.iamprivate == anotherAlpha.iamprivate)
return true;
else
return false;
}
}

public class Test{
public static void main(String args[]){
Alpha aa=new Alpha(10);
Alpha bb=new Alpha(12);

if(aa.isEqualTo(bb)){
System.out.println("equal ");
}
else{
System.out.println("not equal ");
}
}
}

结果是nuo equal

mport java.util.Scanner;

public class Main {

public static void main(String[] args) {
Person p = new Person();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int age = scanner.nextInt();
p.setAge(age);
System.out.println(p.getAge());
}
}

}

class Person {

private int age;

//write your code here......
public void setAge(int age) {
this.age = age;
}
public int getAge() {
if (this.age < 0) {
return 0;
} else if (this.age > 200) {
return 200;
} else {
return this.age;
}
}

}

内部类

public class Outer{ 
private int size;

/** 定义内部类Inner */
public class Inner{

//将外包类的成员变量size递增
public void doStuff(){
size++;
}
}

Inner i=new Inner(); //成员变量i指向Inner类的对象

public void increaseSize(){
i.doStuff(); //调用内部类Inner的方法
}


public static void main(String[] a){
Outer o=new Outer();

for (int i = 0; i<4; i++){
o.increaseSize();
System.out.println("The value of size : "+o.size);
}
}
}

public class Outer{ 
private int size;

/** 定义内部类Inner */
public class Inner{

private int size;

public void doStuff(int size){
size++; //存取局部变量
this.size++; //存取内部类的成员变量
Outer.this.size++; //存取其外包类Outer的成员变量
System.out.println("size in Inner.doStuff(): "+size);
System.out.println("size of the Inner class: "+this.size);
System.out.println("size of the Outer class: "+Outer.this.size);
}
}

Inner i=new Inner(); //成员变量i指向Inner类的对象

public void increaseSize(int s){
i.doStuff(s); //调用内部类Inner的方法
}


public static void main(String[] a){
Outer o=new Outer();

o.increaseSize(10);
}
}

class Outer{ 
private int size=5;

/** 方法makeInner(),返回一内部类对象 */
public Object makeInner(final int finalLocalVar){
int LocalVar=6;

class Inner{

public String toString(){
return ("#<Inner size="+size+

" finalLocalVar="+finalLocalVar+">");
}
}
return new Inner(); //方法makeInner()返回一内部类对象
}


public static void main(String[] args){
Outer outer=new Outer ();
Object obj=outer.makeInner(40);
System.out.println("The object is "+obj.toString());
}
}
class OuterClass {
public int data1;
int data2;
public static int data3;
public void test() {
System.out.println("OuterClass:;test()");
}
//实例内部类
class InnerClass {
public int data1 = 122;//就近原则,若非要外部类中的data1则可以用Outer.this.data1;
public int data4;
int data5;
//public static int data5; // error static是类的成员,Inner和成员是一级的
public static final int data6 = 6;//但需要更高的版本,加上final变成常量了
//实力内部类当中,不能有静态成员变量,非要定义用final
//
public void func() {
System.out.println("InnerClass::func()");
System.out.println(OuterClass.this.data1);
System.out.println(data2);
System.out.println(data3);
System.out.println(data4);
System.out.println(data5);
System.out.println(data6);
}
public void test() {
System.out.println("Inner");
final int size = 10;//定义常量,在编译时就确定了,一旦初始化,不能修改
}
}
}
public class Test {
public static void main(String[] args) {
OuterClass oc = new OuterClass();
System.out.println(oc.data1);
OuterClass.InnerClass ic = oc.new InnerClass();//获取实例内部类对象
ic.func();
}
}
  • 外部类中的任何成员都可以在实例内部类方法中直接访问
  • 实力内部类所在位置与外部类成员位置相同,因此也受public 等访问限制符的约束
  • 在实例内部类中访问同名的成员时优先访问自己的,如果要访问外部类的同名成员,必须用:外部类名.this.同名成员来访问
  • 实例内部类对象必须是在先有外部类对象的前提下才能创建
  • 实力内部类的非静态方法包含了一个指向外部类的引用
  • 外部类中,不能直接访问实例内部了中的成员,如果要访问不许先创建内部类的对象

静态内部类

class OuterClass2 {
public int data1 = 1;
int data2 = 2;
public static int data3 = 3;

public void test() {
System.out.println("out::test");
}

static class InnerClass2 {
public int data4 = 4;
int data5 = 5;
public static int data6 = 6;

public void func() {
System.out.println("inn::test");

/*System.out.println(this.data1);
System.out.println(data2);*///无法访问外部类的非静态成员
//非要访问
OuterClass2 oc3 = new OuterClass2();
System.out.println(oc3.data1);
System.out.println(data3);
System.out.println(data4);
System.out.println(data5);
System.out.println(data6);
}
}

}
public class Test2 {
public static void main(String[] args) {
OuterClass2.InnerClass2 oc2 = new OuterClass2.InnerClass2();//这样不需要先创建外部类对象
oc2.func();
}
}
  • 静态内部类中只能访问外部类中的静态成员
  • 非要访问,得新建一个外部类对象
  • 创建静态内部类是不需要创建外部类对象

局部内部类

public class Test2 {
public static void func1() {
class Inner {
public void test() {
System.out.println("dasdsadsad");
}
}
Inner in = new Inner();
in.test();//只能在方法中使用
}
public static void main(String[] args) {

}
}
  • 局部内部类只能在所定义得方法体内部使用
  • 不能被public,static等修饰
  • 几乎不会被使用

匿名内部类(学完接口回来)


static

  • static 修饰的成员变量称为静态成员变量,最大特性是:不属于某个具体的对象,是所有对象所共享的。
    静态成员变量特征
  • 不属于某个具体的对象,是类的属性,是所有对象所共享的。不存在某个对象的空间中。
  • 既可以通过对象访问,也可以通过类名访问,但一般推荐类名访问
  • 类变量储存在方法区中
  • 生命周期伴随类的一生,随类的加载而创建,随类的卸载而销毁
  • 静态的方法内也不能访问非静态的成员或方法但非静态的可以
  • 静态方法无法重写,不能用来实现多态
  • 初始化要么在类内,要么在类外

代码块

public class Stu {
public String name = "yxz";//就地初始化,但只适合默认的一些量
public int age;

//构造方法
public Stu() {
System.out.println("不带参数的构造方法");
}
{
System.out.println("实例代码块");
}
static {
System.out.println("静态代码块");
}



public static void main(String[] args) {
Stu stu = new Stu();//静态的执行的更快
Stu stu2 = new Stu();//static只会执行1次,赋值时如果都是static就看顺序
}
}

对象的打印

class A {
public int a = 1;
@Override
public String toString() {
return "A{" +
"a=" + a +
'}';
}
public class Test2 {
}
public static void main(String[] args) {
A a = new A();
System.out.println(a);
System.out.println(new OuterClass2());//匿名对象 ,只能使用一次
}
}

右键->生成->toString()

继承

class Animal {
public String name;
public int age;
public void eat() {
System.out.println(name + "正在吃饭!");
}
}
class Dog extends Animal {
public void barks() {
System.out.println(name + "汪汪叫!" + "年龄" + age);
}
}
class Cat extends Animal {
public void catchMouse() {
System.out.println(name + "正在抓老鼠");
}
}
public class jc {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "ctl";
dog.age = 12;
dog.barks();
dog.eat();
}
}
  • 子类会将父类的成员变量和方法继承到子类中
  • 子类继承父类之后,必须要添加自己特有的成员,体现出与基类的不同,否则就没必要继承了。
  • 私有的成员可以被继承但不能访问,所以会报错
class Base {
int a;
int b;
public void methodA() {
System.out.println("Base中的methodA()");
}
}
public class Jc2 extends Base {
int a;
int b;
int c;

public void methodB() {
a = 10;//当父类和字类拥有同名变量时,优先访问类自己的
super.b = 20;
c = 30;

System.out.println(a);
System.out.println(b);
System.out.println(super.b);
System.out.println(c);
}

public static void main(String[] args) {
Jc2 jc2 = new Jc2();

Base base = new Base();
System.out.println();
}
}
class Base {
int a;
int b;
public void methodA() {
System.out.println("Base中的methodA()");
}
}
public class Jc2 extends Base {
/* public void methodA() {
System.out.println("Jc2中的methodA()");
}*/
public void methodB() {
System.out.println("Jc2中的methodB()");
}
public void methodC() {
methodB();// 访问子类自己的methodB()
methodA();// 访问子类继承的methodA()
}

public static void main(String[] args) {
Jc2 jc2 = new Jc2();
jc2.methodC();
}

}

学生选课系统

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Map.Entry;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class CourseSelectionSystem{
Database db;
LoginFrame login_frame;
MainFrame manager_frame;
Teach teach;

public CourseSelectionSystem() throws IOException {
db = new Database("course.txt","score.txt","account.txt");


db.addAccount("teach", "666666", 0, "教务员 "); //增加新账号
db.addAccount("lil", "666666", 1, "李立 ");
db.addAccount("yangf", "666666", 1, "杨帆 ");
db.addAccount("zhangdw", "666666", 1, "张大伟 ");
db.addAccount("wangqs", "666666", 2, "王青松 ");
db.addAccount("chenl", "666666", 2, "陈丽 ");
db.addAccount("wus", "666666", 2, "吴松 ");
db.addAccount("liuq", "666666", 2, "刘强 ");


teach = new Teach(db);
login_frame = new LoginFrame(db, teach);
manager_frame = new MainFrame(db);
login_frame.initFrame(manager_frame);
manager_frame.initFrame(login_frame);
}

public LoginFrame getLogin() {
return login_frame;
}

public static void main(String[] args) throws IOException {
CourseSelectionSystem css = new CourseSelectionSystem();
css.getLogin().setVisible(true);
}
}

class MainFrame extends JFrame{
Database db;
LoginFrame login_frame;
private User user;
private JButton manager_new_course = new JButton("添加课程");
private JButton student_select_course = new JButton("选择课程");
private JButton student_delect_course = new JButton("删除课程");
private JButton teacher_view_course = new JButton("查看选课情况");
private JButton teacher_info_course = new JButton("查看课程信息");
private JButton teacher_score = new JButton("打分");
private JLabel manager_jl_0 = new JLabel();
private JLabel teacher_jl_0 = new JLabel();
private JLabel teacher_jl_1 = new JLabel("选择课程:");
private JLabel student_jl_0_0 = new JLabel();
private JLabel student_jl_0_1 = new JLabel();
private JLabel student_jl_0_2 = new JLabel();
private JTextField manager_jt_course_name = new JTextField();
private JTextField manager_jt_course_info = new JTextField();
private JTextField teacher_jt_score = new JTextField();
private JLabel manager_jl_init = new JLabel();
private JLabel teacher_jl_init = new JLabel();
private JLabel student_jl_init = new JLabel();
private JLabel manager_jl_1 = new JLabel("课程名字\n");
private JLabel manager_jl_2 = new JLabel("课程教师\n");
private JLabel manager_jl_3 = new JLabel("课程信息\n");
private JComboBox manager_jc_teacher = new JComboBox();
private JComboBox teacher_jc_course = new JComboBox();

DefaultListModel student_select_course_dlm = new DefaultListModel();
JList student_select_course_jl = new JList(student_select_course_dlm);
JScrollPane student_select_course_jsp = new JScrollPane(student_select_course_jl);

DefaultListModel student_delect_course_dlm = new DefaultListModel();
JList student_delect_course_jl = new JList(student_delect_course_dlm);
JScrollPane student_delect_course_jsp = new JScrollPane(student_delect_course_jl);

DefaultListModel teacher_score_dlm = new DefaultListModel();
JList teacher_score_jl = new JList(teacher_score_dlm);
JScrollPane teacher_score_jsp = new JScrollPane(teacher_score_jl);

private JPanel menu_cards = new JPanel();
private CardLayout menu_c_layout = new CardLayout();
private JPanel content_cards = new JPanel();
private CardLayout content_c_layout = new CardLayout();

private JPanel manager_cards = new JPanel();
private CardLayout manager_c_layout = new CardLayout();
private JMenuBar manager_menuBar = new JMenuBar();
private JMenu manager_menu = new JMenu("添加课程");
private JPanel manager_init_page = new JPanel();
private JPanel manager_new_course_page = new JPanel();

private JPanel teacher_cards = new JPanel();
private CardLayout teacher_c_layout = new CardLayout();
private JMenuBar teacher_menuBar = new JMenuBar();

private JMenu teacher_menu = new JMenu("教学任务管理");
private JPanel teacher_init_page = new JPanel();
private JPanel teacher_score_page = new JPanel();
private JPanel teacher_score_north = new JPanel();
private JPanel teacher_score_north_course = new JPanel();
private JPanel teacher_score_south = new JPanel();

private JPanel student_cards = new JPanel();
private CardLayout student_c_layout = new CardLayout();
private JMenuBar student_menuBar = new JMenuBar();
private JMenu student_menu_select_course = new JMenu("选课");
private JMenu student_menu_delect_course = new JMenu("退选");
private JMenu student_menu_view_course = new JMenu("View Course");
private JPanel student_init_page = new JPanel();
private JPanel student_select_course_page = new JPanel();
private JPanel student_delect_course_page = new JPanel();
private JPanel student_view_score_page = new JPanel();

public MainFrame(Database db) {
super("选课系统");
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
try {
db.updataAll();
} catch (IOException e1) {

e1.printStackTrace();
}
setVisible(false);
login_frame.setVisible(true);
clear();
}
});
this.db = db;

setLocation(800,400);

setLayout(new BorderLayout());
menu_cards.setLayout(menu_c_layout);
content_cards.setLayout(content_c_layout);
add("North",menu_cards);
add("Center",content_cards);


initManagerPage();
initTeacherPage();
initStudentPage();

pack();
}

private void initTeacherPage() {
teacher_score_jl.setCellRenderer(new ScoreCellRenderer());
teacher_jc_course.setRenderer(new CourseTeaCellRenderer());

teacher_menuBar.add(teacher_menu);
teacher_menu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
teacher_c_layout.show(teacher_cards, "teacher_score_page");
}
@Override
public void menuDeselected(MenuEvent e) {

}
@Override
public void menuCanceled(MenuEvent e) {

}
});
menu_cards.add("teacher_menuBar",teacher_menuBar);

//manager_cards manager_init_page
teacher_init_page.add(teacher_jl_init);

//manager_cards manager_new_course_page
teacher_score_page.setLayout(new BorderLayout());
teacher_view_course.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Teacher t = (Teacher) user;
reloadScoreTea(t, (int)teacher_jc_course.getSelectedItem());
}
});
teacher_info_course.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Teacher t = (Teacher) user;
t.getCourseInfo((int)teacher_jc_course.getSelectedItem());
JOptionPane.showMessageDialog(null, "<html><body>"+"课程编号: "+t.getCourseInfo((int)teacher_jc_course.getSelectedItem()).get(1)
+"<br>"+"课程名称: "+t.getCourseInfo((int)teacher_jc_course.getSelectedItem()).get(0)
+"<br>"+"课程信息: "+t.getCourseInfo((int)teacher_jc_course.getSelectedItem()).get(2)+"<body></html>");//t.getCourseInfo((int)teacher_jc_course.getSelectedItem()).toString()
}
});
teacher_score.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Teacher t = (Teacher) user;
t.scoreStuCourse((int)((List)teacher_score_jl.getSelectedValue()).get(0), (int)((List)teacher_score_jl.getSelectedValue()).get(1), Integer.parseInt(teacher_jt_score.getText()));
reloadScoreTea(t, (int)teacher_jc_course.getSelectedItem());
}
});

teacher_score_north.setLayout(new BorderLayout());

teacher_score_north_course.setLayout(new GridLayout(2,2));
teacher_score_north_course.add(teacher_jl_1);
teacher_score_north_course.add(teacher_jc_course);
teacher_score_north_course.add(teacher_view_course);
teacher_score_north_course.add(teacher_info_course);
teacher_score_south.setLayout(new GridLayout(1,0));
teacher_score_south.add(teacher_jt_score);
teacher_score_south.add(teacher_score);

teacher_score_north.add("North",teacher_jl_0);
teacher_score_north.add("Center",teacher_score_north_course);
teacher_score_page.add("North",teacher_score_north);
teacher_score_page.add("Center",teacher_score_jsp);
teacher_score_page.add("South",teacher_score_south);


teacher_cards.setLayout(teacher_c_layout);
teacher_cards.add("teacher_init_page",teacher_init_page);
teacher_cards.add("teacher_score_page",teacher_score_page);

content_cards.add("teacher_cards",teacher_cards);
}

private void initStudentPage() {
student_select_course_jl.setCellRenderer(new CourseSelCellRenderer());
student_delect_course_jl.setCellRenderer(new CourseDelCellRenderer());

//student_cards student_menuBar
student_menuBar.add(student_menu_select_course);
student_menuBar.add(student_menu_delect_course);
student_menu_select_course.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
reloadCourseStuNotSelectedList((Student) user);
student_c_layout.show(student_cards, "student_select_course_page");
}
@Override
public void menuDeselected(MenuEvent e) {

}
@Override
public void menuCanceled(MenuEvent e) {

}
});
student_menu_delect_course.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
reloadScoreStuList((Student) user);
student_c_layout.show(student_cards, "student_delect_course_page");
}
@Override
public void menuDeselected(MenuEvent e) {

}
@Override
public void menuCanceled(MenuEvent e) {

}
});
student_menu_view_course.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
student_c_layout.show(student_cards, "student_view_course_page");
}
@Override
public void menuDeselected(MenuEvent e) {

}
@Override
public void menuCanceled(MenuEvent e) {

}
});
menu_cards.add("student_menuBar",student_menuBar);

//student_cards student_init_page
student_init_page.add(student_jl_init);

//student_cards student_select_course_page
student_select_course_page.setLayout(new BorderLayout());
student_select_course.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Student s = (Student)user;
HashMap<Integer, List> stu_not_course = s.getCourseStuNotSelected();
s.selStuCourse(((Entry<Integer, List>)student_select_course_jl.getSelectedValue()).getKey());
reloadCourseStuNotSelectedList(s);
}
});

//student_cards student_delect_course_page
student_delect_course_page.setLayout(new BorderLayout());
student_delect_course.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Student s = (Student)user;
s.delStuCourse((int)((List)student_delect_course_jl.getSelectedValue()).get(1));
reloadScoreStuList(s);
}
});

student_select_course_page.add("North",student_jl_0_0);
student_select_course_page.add("Center",student_select_course_jsp);
student_select_course_page.add("South",student_select_course);

student_delect_course_page.add("North",student_jl_0_1);
student_delect_course_page.add("Center",student_delect_course_jsp);
student_delect_course_page.add("South",student_delect_course);

student_view_score_page.add(student_jl_0_2);

student_cards.setLayout(student_c_layout);
student_cards.add("student_init_page",student_init_page);
student_cards.add("student_select_course_page",student_select_course_page);
student_cards.add("student_delect_course_page",student_delect_course_page);

content_cards.add("student_cards",student_cards);
}

private void initManagerPage() {
manager_jc_teacher.setRenderer(new TeaCellRenderer());

//manager_cards manager_menuBar
manager_menuBar.add(manager_menu);
manager_menu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
manager_c_layout.show(manager_cards, "manager_new_course_page");
}
@Override
public void menuDeselected(MenuEvent e) {

}
@Override
public void menuCanceled(MenuEvent e) {

}
});
menu_cards.add("manager_menuBar",manager_menuBar);

//manager_cards manager_init_page
manager_init_page.add(manager_jl_init);

//manager_cards manager_new_course_page
manager_new_course_page.setLayout(new GridLayout(0,1));
manager_new_course.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Entry<Integer,String> t = (Entry<Integer, String>) manager_jc_teacher.getSelectedItem();
Manager m = (Manager)user;
m.newCourse(manager_jt_course_name.getText(), t.getKey(), manager_jt_course_info.getText());
manager_jt_course_name.setText("");
manager_jt_course_info.setText("");
JOptionPane.showMessageDialog(null, "课程添加成功!");
}
});

manager_new_course_page.add(manager_jl_0);
manager_new_course_page.add(manager_jl_1);
manager_new_course_page.add(manager_jt_course_name);
manager_new_course_page.add(manager_jl_2);
manager_new_course_page.add(manager_jc_teacher);
manager_new_course_page.add(manager_jl_3);
manager_new_course_page.add(manager_jt_course_info);
manager_new_course_page.add(manager_new_course);

manager_cards.setLayout(manager_c_layout);
manager_cards.add("manager_init_page",manager_init_page);
manager_cards.add("manager_new_course_page",manager_new_course_page);

content_cards.add("manager_cards",manager_cards);
}
// 设置当前用户,由登录界面调用
public void setUser(User user) {
this.user = user;
if(user.getType()==0) {
setTeacherList();
manager_jl_0.setText("管理员:"+user.getUsername()+" 编号:"+user.getUserId());
manager_jl_init.setText("<html><body>"+"欢迎来到选课系统<br>"+"管理员:"+user.getUsername()+" 编号:"+user.getUserId()+"<br>请选择功能"+"<body></html>");

content_c_layout.show(content_cards, "manager_cards");
menu_c_layout.show(menu_cards, "manager_menuBar");
manager_c_layout.show(manager_cards, "manager_init_page");
}
else if(user.getType()==1) {
setTeacherList_course();
teacher_jl_0.setText("教师: "+user.getUsername()+" 编号:"+user.getUserId());
teacher_jl_init.setText("<html><body>"+"欢迎来到选课系统<br>"+"教师: "+user.getUsername()+" 编号:"+user.getUserId()+"<br>请选择功能"+"<body></html>");

content_c_layout.show(content_cards, "teacher_cards");
menu_c_layout.show(menu_cards, "teacher_menuBar");
teacher_c_layout.show(teacher_cards, "teacher_init_page");
}
else if(user.getType()==2) {
student_jl_0_0.setText("学生姓名:"+user.getUsername()+" 编号:"+user.getUserId());
student_jl_0_1.setText("学生姓名:"+user.getUsername()+" 编号:"+user.getUserId());
student_jl_0_2.setText("学生姓名:"+user.getUsername()+" 编号:"+user.getUserId());
student_jl_init.setText("<html><body>"+"欢迎来到选课系统<br>"+"学生: "+user.getUsername()+" 编号: "+user.getUserId()+"<br>请选择功能"+"<body></html>");

content_c_layout.show(content_cards, "student_cards");
menu_c_layout.show(menu_cards, "student_menuBar");
student_c_layout.show(student_cards, "student_init_page");
}
}

public void setTeacherList() {
manager_jc_teacher.removeAllItems();
HashMap<Integer, String> teacher = db.getTeacher();
for(Entry<Integer, String> entry:teacher.entrySet()) {
manager_jc_teacher.addItem(entry);
}
}

//更新教师界面中选中课程的选课信息
public void reloadScoreTea(Teacher t, int course_id) {
teacher_score_dlm.clear();
ArrayList<List> teacher_course = t.getScoreTeacher(course_id);
for(List l:teacher_course) {
teacher_score_dlm.addElement(l);
}
}

public void setTeacherList_course() {
teacher_jc_course.removeAllItems();
List<Integer> teacher_course = db.getTeacherCourse(user.getUserId());
for(int l:teacher_course) {
teacher_jc_course.addItem(l);
}
}

// 更新学生界面中学生可选课程列表
public void reloadCourseStuNotSelectedList(Student s) {
student_select_course_dlm.clear();

HashMap<Integer, List> course = s.getCourseStuNotSelected();
for(Entry<Integer, List> entry:course.entrySet()) {
student_select_course_dlm.addElement(entry);
}
}

// 更新学生界面中学生已选课程列表
public void reloadScoreStuList(Student s) {
student_delect_course_dlm.clear();
ArrayList<List> student_score = s.getScoreStu();
for(List l:student_score) {
student_delect_course_dlm.addElement(l);
}
}

public void initFrame(LoginFrame login_frame) {
this.login_frame = login_frame;
}

// 清空该用户信息。退出界面时调用
public void clear() {
teacher_score_dlm.clear();
manager_jt_course_name.setText(null);
manager_jt_course_info.setText(null);
teacher_jt_score.setText(null);
user = null;
}
}


class LoginFrame extends JFrame{
private MainFrame manager_frame;
private JTextField tf_user = new JTextField();
private JPasswordField tf_pwd = new JPasswordField();
private JButton login = new JButton("登录"); // 用户登录
private JLabel jl = new JLabel();
private JLabel jl_login = new JLabel("");
private Database db;
private Teach teach;
private User u;
public LoginFrame(Database db, Teach teach) {
super("选课系统登录");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.db = db;
this.teach = teach;
setLayout(new GridLayout(0,1));

setLocation(800,400);
setSize(250,200);
login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
User user = verifyUser(tf_user.getText(), String.valueOf(tf_pwd.getPassword()));
if(user==null) {
jl.setText("user or pwd error");
}
else {
tf_user.setText(null);
tf_pwd.setText(null);
setVisible(false);
manager_frame.setUser(user);
manager_frame.setVisible(true);
jl.setText(null);
}
}

});
add(tf_user);
add(tf_pwd);
add(login);
add(jl);
}

public void initFrame(MainFrame manager_frame) {
this.manager_frame = manager_frame;
}
// 验证用户名密码。如果正确,返回用户对象;如果错误,返回null
public User verifyUser(String user, String pwd) {
List account = db.getAccount(user);
u = null;
if(account == null) {
return null;
}
else if(pwd.compareTo((String)account.get(0))==0){
if((int)account.get(1) == 0) {
u = new Manager(user, pwd, (int)account.get(1),(int)account.get(2),(String)account.get(3), teach);
}
else if((int)account.get(1) == 1) {
u = new Teacher(user, pwd, (int)account.get(1),(int)account.get(2),(String)account.get(3), teach);
}
else if((int)account.get(1) == 2) {
u = new Student(user, pwd, (int)account.get(1),(int)account.get(2),(String)account.get(3), teach);
}
return u;
}
return null;
}
}

class User{
String user; // 用户名
String pwd; // 密码
int type; // 用户类型
int account_id; // 用户编号
String account_name; // 用户名字
Teach teach;

public User(String user, String pwd, int type, int account_id, String account_name, Teach teach) {
this.user = user;
this.pwd = pwd;
this.type = type;
this.account_id = account_id;
this.account_name = account_name;
this.teach = teach;
}

public int getType() {
return type;
}

public String getUser() {
return user;
}

public String getUsername() {
return account_name;
}

public int getUserId() {
return account_id;
}
}

class Student extends User{
public Student(String user, String pwd, int type, int account_id, String account_name, Teach teach) {
super(user, pwd, type, account_id, account_name, teach);
}
// 学生选课。如果成功,返回1,如果失败,返回-1
public int selStuCourse(int course_id) {
teach.selStuCourse(account_id, course_id);
return 1;
}
// 查询学生可选课程。 返回可选课程字典
public HashMap<Integer, List> getCourseStuNotSelected(){
return teach.getCourseStuNotSelected(account_id);
}
// 学生退课。如果成功,返回1,如果失败,返回-1
public int delStuCourse(int course_id) {
teach.delStuCourse(account_id, course_id);
return 1;
}
// 查询学生所选课程信息。 返回所选课程列表
public ArrayList<List> getScoreStu() {
return teach.getScoreStu(account_id);
}
}

class Teacher extends User{
public Teacher(String user, String pwd, int type, int account_id, String account_name, Teach teach) {
super(user, pwd, type, account_id, account_name, teach);
}
// 查询课程所有学生成绩。 返回成绩列表
public ArrayList<List> getScoreTeacher(int course_id) {
return teach.getScoreTeacher(course_id);
}
// 查询选中课程详细信息。返回课程信息
public List getCourseInfo(int course_id) {
return teach.getCourseInfo(course_id);
}
// 教师对学生课程打分。
public void scoreStuCourse(int student_id, int course_id, int student_score) {
teach.scoreStuCourse(student_id, course_id, student_score);
}
}

class Manager extends User{
public Manager(String user, String pwd, int type, int account_id, String account_name, Teach teach) {
super(user, pwd, type, account_id, account_name,teach);
}
// 新建课程。如果成功,返回课程编号,如果失败,返回-1
public int newCourse(String course_name, int teacher_id , String course_info) {
teach.newCourse(course_name, teacher_id, course_info);
return 1;
}
}

class Teach{
private Database db;
public Teach(Database db) {
this.db = db;
}
// 新建课程,进行检查并进行数据库存入。如果成功,返回课程编号,如果失败,返回-1
public int newCourse(String course_name, int teacher_id , String course_info) {
db.addCourse(course_name, teacher_id, course_info);
return 1;
}
// 学生选课,进行检查并进行数据库存入。如果成功,返回1,如果失败,返回-1
public int selStuCourse(int account_id, int course_id) {
db.addStuCourse(account_id, course_id);
return 1;
}
// 学生退课,进行检查并进行数据库存入。如果成功,返回1,如果失败,返回-1
public int delStuCourse(int account_id, int course_id) {
db.delStuCourse(account_id, course_id);
return 1;
}
// 教师对学生课程打分。
public int scoreStuCourse(int student_id, int course_id, int student_score) {
if(student_score<-1 | student_score>100) {
JOptionPane.showMessageDialog(null, "请输入0-100的整数");
return -1;
}
else {
db.addStuScore(student_id, course_id, student_score);
return 1;
}
}
// 查询课程详细信息。返回课程信息
public List getCourseInfo(int course_id) {
return db.getCourse().get(course_id);
}
// 查询课程所有学生成绩。 返回成绩列表
public ArrayList<List> getScoreTeacher(int course_id) {
return db.getScoreCourse(course_id);
}
// 查询学生可选课程。 返回可选课程字典
public HashMap<Integer, List> getCourseStuNotSelected(int account_id){
return db.getCourseNotSelected(account_id);
}
// 查询学生所选课程信息。 返回所选课程列表
public ArrayList<List> getScoreStu(int account_id) {
return db.getScoreStu(account_id);
}
}

class Database {
// 存储文件
private File data_course;
private File data_score;
private File data_account;
// 当前最大编号,用于新增时
private int course_id = 0;
private int student_id = 0;
private int teacher_id = 0;
private int manager_id = 0;
// 运行时数据存储
private HashMap<Integer, List> course = new HashMap<Integer, List>();
private HashMap<String, List> account = new HashMap<String, List>();
private HashMap<Integer, String> manager = new HashMap<Integer, String>();
private HashMap<Integer, String> teacher = new HashMap<Integer, String>();
private HashMap<Integer, String> student = new HashMap<Integer, String>();
private ArrayList<List> score = new ArrayList<List>();

// 参数:存储文件位置
public Database(String file_course, String file_score, String file_account) throws IOException {
this.data_course = new File(file_course);
this.data_score = new File(file_score);
this.data_account = new File(file_account);
this.readIn();
}

public HashMap<Integer, List> getCourse() {
return course;
}

public HashMap<Integer, List> getCourseNotSelected(int student_id) {
HashMap<Integer, List> map_copy = (HashMap<Integer, List>) course.clone();
System.out.println(map_copy.toString());
for(List l: score) {
if((int)l.get(0)==student_id) {
map_copy.remove((int)l.get(1));
}
}
System.out.println(map_copy.toString());
return map_copy;
}

public List getTeacherCourse(int teacher_id) {
List teacher_course_list = new ArrayList();
for(Entry<Integer, List> entry: course.entrySet()) {
if((int)entry.getValue().get(1)==teacher_id) {
teacher_course_list.add((int)entry.getKey());
}
}
return teacher_course_list;
}


public ArrayList<List> getScoreCourse(int course_id) {
ArrayList<List> list_copy = new ArrayList();
for(List l : score) {
if((int)l.get(1)==course_id) {
list_copy.add(l);
}
}
return list_copy;
}

public HashMap<Integer, String> getTeacher() {
return teacher;
}

public HashMap<Integer, String> getStudent() {
return student;
}

public ArrayList<List> getScore(int student_id) {
ArrayList<List> list_copy = new ArrayList();
for(List l : score) {
if((int)l.get(0)==student_id) {
list_copy.add(l);
}
}
return list_copy;
}

public ArrayList<List> getScoreStu(int student_id) {
ArrayList<List> list_copy = new ArrayList();
for(List l : score) {
if((int)l.get(0)==student_id) {
list_copy.add(l);
}
}
return list_copy;
}

public HashMap<String, List> getAccount() {
return account;
}


public List getAccount(String user) {
return account.get(user);
}

//从文件中读入课程、用户名等数据
public void readIn() throws IOException {
RandomAccessFile raf_course = new RandomAccessFile(data_course,"rw");
RandomAccessFile raf_score = new RandomAccessFile(data_score,"rw");
RandomAccessFile raf_account = new RandomAccessFile(data_account,"rw");

long fileLength = raf_course.length();
long filePoint = 0;
int course_id;
String course_name;
int course_teacher_id;
String course_info;
raf_course.seek(0);
if(filePoint < fileLength) {
this.course_id = Integer.parseInt(raf_course.readLine());
}
while(filePoint < fileLength) {
course_id = Integer.parseInt(raf_course.readLine());
course_name = raf_course.readLine();
course_name = new String(course_name.getBytes("ISO-8859-1"),"gbk");
course_teacher_id = Integer.parseInt(raf_course.readLine());
course_info = raf_course.readLine();
course_info = new String(course_info.getBytes("ISO-8859-1"),"gbk");
course.put(course_id, Arrays.asList(course_name,course_teacher_id,course_info));
filePoint = raf_course.getFilePointer();
}
raf_course.close();

fileLength = raf_account.length();
filePoint = 0;
String account_user;
String account_pwd;
int account_type;
Integer account_id;
String account_name;

raf_account.seek(0);
if(filePoint < fileLength) {
this.manager_id = Integer.parseInt(raf_account.readLine());
this.teacher_id = Integer.parseInt(raf_account.readLine());
this.student_id = Integer.parseInt(raf_account.readLine());
filePoint = raf_account.getFilePointer();
}
while(filePoint < fileLength) {
account_user = raf_account.readLine();
account_user = new String(account_user.getBytes("ISO-8859-1"),"gbk");
account_pwd = raf_account.readLine();
account_pwd = new String(account_pwd.getBytes("ISO-8859-1"),"gbk");
account_type = Integer.parseInt(raf_account.readLine());
account_id = Integer.parseInt(raf_account.readLine());
account_name = raf_account.readLine();
account_name = new String(account_name.getBytes("ISO-8859-1"),"gbk");
switch(account_type) {
case 0:
manager.put(account_id, account_name);
break;
case 1:
teacher.put(account_id, account_name);
break;
case 2:
student.put(account_id, account_name);
break;
}
account.put(account_user, Arrays.asList(account_pwd, account_type, account_id,account_name));
filePoint = raf_account.getFilePointer();
}
raf_account.close();


fileLength = raf_score.length();
filePoint = 0;
int student_id;
int student_course_id;
int student_score;
raf_score.seek(0);
while(filePoint < fileLength) {
student_id = Integer.parseInt(raf_score.readLine());
student_course_id = Integer.parseInt(raf_score.readLine());
student_score = Integer.parseInt(raf_score.readLine());
score.add(Arrays.asList(student_id,student_course_id,student_score));
filePoint = raf_score.getFilePointer();
}
raf_score.close();
}

//创建用户
public void addAccount(String account_user, String account_pwd, int account_type, String account_name) throws IOException {
int id = -1;
if(!account.containsKey(account_user)) {
switch(account_type) {
case(0):
manager_id = manager_id+1;
id = manager_id;
manager.put(id, account_name);
break;
case(1):
teacher_id = teacher_id+1;
id = teacher_id;
teacher.put(id, account_name);
break;
case(2):
student_id = student_id+1;
id = student_id;
student.put(id, account_name);
break;
}
account.put(account_user, Arrays.asList(account_pwd, account_type, id, account_name));
}else {
System.out.println("Account "+account_user+" has already exists.");
}
updateAccountData();
}

public void addCourse(String course_name, int course_teacher_id, String course_info) {
course_id = course_id + 1;
course.put(course_id, Arrays.asList(course_name, course_teacher_id, course_info));
}

public void addStuCourse(int student_id, int course_id) {
score.add(Arrays.asList(student_id, course_id, -1));
}

public void delStuCourse(int student_id, int course_id) {
System.out.println("del "+student_id+" "+course_id);
Iterator<List> i = score.iterator();
while(i.hasNext()){
List l = i.next();
if((int)l.get(0)==student_id & (int)l.get(1)==course_id){
i.remove();
}
}
}


public void addStuScore(int student_id, int course_id, int student_score) {
for(List<Integer> l:score) {
if(l.get(0)==student_id & l.get(1)==course_id) {
l.set(2, student_score);
return;
}
}
}

public void clearFile(File file) throws IOException {
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
}

private void updateCourseData() throws IOException {
clearFile(data_course);
RandomAccessFile raf_course = new RandomAccessFile(data_course,"rw");
raf_course.writeBytes(course_id+"\n");

for(int key:course.keySet()) {
raf_course.write((key+"\n").getBytes());
raf_course.write((course.get(key).get(0)+"\n").getBytes());
raf_course.write((course.get(key).get(1)+"\n").getBytes());
raf_course.write((course.get(key).get(2)+"\n").getBytes());
}
raf_course.close();
}


private void updateScoreData() throws IOException {
clearFile(data_score);
RandomAccessFile raf_score = new RandomAccessFile(data_score,"rw");

for(List l:score) {
raf_score.write((l.get(0)+"\n").getBytes());
raf_score.write((l.get(1)+"\n").getBytes());
raf_score.write((l.get(2)+"\n").getBytes());
}
raf_score.close();
}

//更新课程数据
private void updateAccountData() throws IOException {
clearFile(data_account);
RandomAccessFile raf_account = new RandomAccessFile(data_account,"rw");


raf_account.writeBytes(manager_id+"\n");
raf_account.writeBytes(teacher_id+"\n");
raf_account.writeBytes(student_id+"\n");

for(String key:account.keySet()) {
raf_account.write((key+"\n").getBytes());
raf_account.write((account.get(key).get(0)+"\n").getBytes());
raf_account.write((account.get(key).get(1)+"\n").getBytes());
raf_account.write((account.get(key).get(2)+"\n").getBytes());
raf_account.write((account.get(key).get(3)+"\n").getBytes());
}
raf_account.close();
}

// 文件内容更新
public void updataAll() throws IOException {
updateCourseData();
updateScoreData();
updateAccountData();
System.out.println("update finish");
}
}

class ScoreCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
List<Integer> ci = (List<Integer>) value;

this.setText("学生编号: "+ci.get(0)+" 分数: "+ci.get(2));
return this;
}
}


class CourseTeaCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Integer ci = (Integer) value;

this.setText("课程编号: "+ci);
return this;
}
}


class CourseSelCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Entry<Integer, List> ci = (Entry<Integer, List>) value;

this.setText("课程编号: "+ci.getKey()+" 课程名称: "+ci.getValue().get(0)+" 教师编号: "+ci.getValue().get(1)+" 课程信息: "+ci.getValue().get(2));
return this;
}
}


class CourseDelCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
List ci = (List) value;

this.setText("课程编号: "+ci.get(1)+" 分数: "+ci.get(2));
return this;
}
}


class TeaCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Entry<Integer, String> ci = (Entry<Integer, String>) value;

this.setText("编号: "+ci.getKey()+" 姓名: "+ci.getValue());
return this;
}
}