1. Java学习自测
2.程序填空是图形shape那个输出面积的那个
某绘图系统存在Point、Line、Square三种图元,它们具有Shape接口,图元的类图关系如图5-1所示。现要将Circle图元加入此绘图系统以实现功能扩充。已知某第三方库已经提供了XCircle不是由Shape派生而来,它提供了的接口不被系统直接使用。代码5-1既使用了XCircle又遵循了Shape规定的接口,即避免了从头开发一个新的Circle类,又可以不修改绘图系统中已经定义的接口。代码5-2根据用户指定的参数生成特定的图元实例,并对之进行显示操作
第三方库
Shape
display()显示图元
XCircle DisplayIt()显示图元
class Circle _implements shape__(1)___{
private __Xcircle_(2)___pxc;
public Circle ( ) {
pxc = new __Xcircle()_(3)___;
}
public void display(){
pxc.(4)_DisplayIt()__;
}
}
public class Factory{
public Shape(5)getShapeInstance(int type){
//生成特定类
switch(type){
case 0:return new point();
case 1:return new Rectangle();
case 2:return new Line();
case 3:return new Circle();
default:return null;
}
}
}
public class App{
public static void main(String argv[]){
if(argv.length !=1){
System.out.println("error ");
return;}
int type=(new Integer(argv[0])).intValue();
Factory factory=new Factory();
Shape s;
s= factory.getShapeInstance(type)(6)__;
if(s==null){
System.out.println(“Error ”);return;}
s.display();
return;
}
}
3、高于平均分的人作为函数值返回,高于平均分的分数放在up所指的数组中。并在类中编写main函数,对所编写的函数进行测试。
package com.example.demo;
import java.util.ArrayList;
import java.util.Arrays;
//高于平均分的人作为函数值返回,高于平均分的分数放在up所指的数组中。并在类中编写main函数,对所编写的函数进行测试
public class ArrayLists {
public static void main(String[] args) {
int a[] =new int[]{1,5,6,9,12,6,8};
int average = getAverage(a);
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if(average<a[i]){
list.add(a[i]);
}
}
System.out.println(list);
System.out.println(getAverage(a));;
}
public static int getAverage(int[] a){
int sum=0;
for (int i = 0; i < a.length; i++) {
sum+=a[i];
}
return sum/a.length;
}
}
4、java多线程技术,创建线程t和s,分别在控制台上显示字符串“您好”和“他好”,分别暂停的时间为25mm(毫秒)和15mm(毫秒),分别显示20次
package com.example.demo;
//java多线程技术,创建线程t和s,分别在控制台上显示字符串“您好”和“他好”,分别暂停的时间为25mm(毫秒)和15mm(毫秒),分别显示20次
public class ThreadTest {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
int count=20;
@Override
public void run() {
while(true&&count-->0){
System.out.println("你好");
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread s = new Thread(new Runnable() {
int count=20;
@Override
public void run() {
while(true&&count-->0) {
System.out.println("他好");
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
s.start();
t.start();
}
}
五、创建一个圆的类,半径设置为私有数据域(实数类型),并有相关的访问器和修改器。通过其构造器,能够构建一个默认的圆对象(默认半径为1)也能构建一个指定的半径的圆对象,并能够记录创建圆对象的总个数提供返回圆的面积,返回圆的周长的方法,其中涉及PI的取值,使用java.lang.Math类属性的PI值。
package com.example.demo;
public class Circle {
private int radius;
public static int count=0;
public static final double PI= Math.PI;
public Circle() {
this.radius=1;
count++;
}
public Circle(int radius) {
this.radius = radius;
count++;
}
public double area(){
return PI*Math.pow(this.radius,2);
}
public double perimeter(){
return 2*PI*this.radius;
}
public static void main(String[] args) {
Circle circle = new Circle();
Circle circle2 = new Circle(2);
System.out.println(circle.radius+"area:"+ circle.area()+"perimeter:"+circle.perimeter()+"count:"+circle.count);
System.out.println(circle2.radius+"area:"+ circle2.area()+"perimeter:"+circle2.perimeter()+"count:"+circle2.count);
}
}
七、设计一个停车场的收费模拟系统,给出响应类的设计和实现。一直停车场有三种车型收费者会根据不同的车型收取不同的停车费,其中客车:15元/小时,货车:12元/小时,轿车:3元/小时
package com.example.demo;
public class Car {
public int fee;
public Car(int fee) {
this.fee = fee;
}
}
package com.example.demo;
public class Bus extends Car{
public Bus(int fee) {
super(fee);
}
}
package com.example.demo;
public class truck extends Car{
public truck(int fee) {
super(fee);
}
}
package com.example.demo;
public class PrivateCar extends Car{
public PrivateCar(int fee) {
super(fee);
}
}
package com.example.demo;
//七、设计一个停车场的收费模拟系统,给出响应类的设计和实现。一直停车场有三种车型收费者会根据不同的车型收取不同的停车费,其中客车:15元/小时,货车:12元/小时,轿车:3元/小时
public class ParkTest {
public static void main(String[] args) {
int charge = charge(new Bus(15));
System.out.println(charge);
}
public static int charge(Car car){
return car.fee;
}
}
-
某公司想开发一个飞机模拟系统,飞机特点如下
interface FlyBehavior {public void fly();};
class SubSonicFly implements FlyBehavior{
public void fly(){
System.out.println(“亚音速飞行!”);
}
}
class SuperSonicFlyimplements FlyBehavior{
public void fly(){
System.out.println(“超音速飞行!”);
}
}
interface TakeOffBehavior {
public void takeOff ();
}
class VerticalTakeOff implements TakeOffBehavior {
public void takeOff (){
System.out.println(“垂直起飞!”);
}
}
class LongDistanceTakeOff implements
TakeOffBehavior {
public void takeOff (){
System.out.println(“长距离起飞!”);
}
}
abstract class AirCraft{
protected (1FlyBehavior) flyBehavior; //飞行
protected(2TakeOffBehavior)takeOffBehavior; //起飞
public void fly(){(3)flyBehavior.fly();}
Public void takeoff(){ (4)takeOffBehavior.takeoff(); }
}
class Helicopter (5extends) AirCraft{
public Helicopter(){
flyBehavior=new (6SuperSonicFly()); takeOffBehavior=new (7VerticalTakeOff());
}
}
-
一维数组控制台输入求最大值和逆序
package myArray;
import java.util.Scanner;
public class Array {
public void test01()
{
final int N=5;
int score[] = new int[N];
Scanner reader = new Scanner(System.in);
System.out.println("Input " + N + "number ,Please:");
for(int i=0;i<N;i++)
score[i] = reader.nextInt();
//1.寻找最大值
int max;
max = score[0];
for(int i=1;i<score.length;i++)
if(score[i] > max) max = score[i];
System.out.println("max="+max);
//2.数组逆序
int temp;
for (int i = 0; i < score.length / 2; i++) {
temp = score[i];
score[i] = score[score.length - i - 1];
score[score.length - i - 1] = temp;
}
for(int i : score)
{
System.out.println(i);
}
}
public static void main(String[] args)
{
Array arr = new Array();
arr.test01();
}
}
-
对数组的一些操作Arrays
import java.util.Arrays;
/*
数组初始化
1.动态初始化(指定长度)格式:数组类型 [] 数组名称 = new 数据类型[数组长度];int [] arr = new int [15];
2.静态初始化(指定内容)格式:数组类型 [] 数组名称 = new 数据类型[]{内容};string [] arr1= new string []{"str","yel"};
省略格式:string [] arr1= {"yel","he"};
注意事项:
1.静态初始化可以自动得到长度
2.静动态都可初始化可以拆分两个步骤
3.静态初始化一旦使用省略格式不能拆分两个步骤
string [] a;
a={"abc","vvv"};//错误
java 内存分配需要五个区
栈:存放方法的局部变量,方法的运行一定在栈中运行的
堆:凡是new出来的东西,都在堆里面
方法区:存储.class相关信息,包含方法的信息
获取数组长度 arr.length;
*/
public class ArrayInit {
public static void main(String[] args) {
int a[] =new int[]{311, 349, 67, 647, 112};
String []s = new String[]{"soup","tang"};
System.out.println(s);//打印的是s[0]地址,数组没有重写toString方法
System.out.println(Arrays.toString(s));//[soup, tang]
System.out.println(s.length);
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int index = Arrays.binarySearch(a, 349);
System.out.println("索引:"+index);
Arrays.fill(a,4,5,1);//将a数组的索引4-5值变成1(左闭右开)
System.out.println(Arrays.toString(a));
}
}
-
二维数组转置
package myArray;
import java.util.Random;
import java.util.Scanner;
public class TwoArray {
public int[][] test01()
{
final int N=3,M=3;
int a[][]=new int[N][M];
//定义扫描器,获取数组元素
Scanner reader=new Scanner(System.in);
//输入数组
System.out.println("Input "+N+"*"+M+" number ,Please:");
for(int i=0;i<a.length;i++)
for(int j=0;j<a[i].length;j++)
a[i][j]=reader.nextInt();
System.out.println("数组中元素是");
int max,row,col;
max=a[0][0];
row=col=1;
//寻找最大值,并打印最大值元素所在的行与列
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
System.out.printf("%5d",a[i][j]); //打印数组中的元素
if(a[i][j]>max){max=a[i][j];row=i+1;col=j+1;} //比较得最大值
}
System.out.println();
}
System.out.println("row="+row+" col="+col+" max="+max); //输出最大值所在的行与列
return a;
}
public static void zhuanZhi(int a[][]) {
//将二维数组(方阵)转置,对角线互换
int temp;
for(int i=1;i<a.length;i++)
for(int j=0;j<i;j++) {
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
System.out.println("---转置后得矩阵为---");
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
System.out.printf("%5d",a[i][j]);
}
System.out.println();
}
}
public static int GetEvenNum(int num1,int num2)
{
Random s = new Random();
int i = s.nextInt(num2 - num1)+1;
if (i % 2==0) return i; //如果是偶数,直接返回
else return i+1; //如果是奇数,加1后返回
}
public static void main(String[] args) {
TwoArray twoarr = new TwoArray();
int[][] a = twoarr.test01();
twoarr.zhuanZhi(a);
System.out.println("任意一个2~32之间的数:"+ GetEvenNum(2,5));
}
}
-
socket
服务器端
package socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
String[] answer ={"喜马拉雅山高8848.43米","48个","青海省"};
ServerSocket sForClient = null;
Socket socketOnServer =null;
DataOutputStream out = null;
DataInputStream in =null;
try{
sForClient = new ServerSocket(2022);
}catch (IOException e){
System.out.println("端口被占用。。。。");
}
try{
System.out.println("等待客户呼叫");
socketOnServer=sForClient.accept();//阻塞状态
System.out.println("客户机地址"+socketOnServer.getInetAddress());
System.out.println("客户机端口"+socketOnServer.getPort());
out=new DataOutputStream(socketOnServer.getOutputStream());
in=new DataInputStream(socketOnServer.getInputStream());
for (int i = 0; i <answer.length ; i++) {
String s = in.readUTF();
System.out.println("服务器收到客户端提问"+s);
out.writeUTF(answer[i]);
Thread.sleep(1000);
}
}catch (Exception e) {
System.out.println("客户端已断开");
}finally{
try{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
if(socketOnServer!=null){
socketOnServer.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
客户端
package socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
String[] mess ={"喜马拉雅山高多少米","亚洲多少个国家","西宁位于哪里"};
Socket mysocket =null;
DataOutputStream out = null;
DataInputStream in =null;
try{
mysocket=new Socket("127.0.0.1",2022);
out=new DataOutputStream(mysocket.getOutputStream());
in=new DataInputStream(mysocket.getInputStream());
for (int i = 0; i <mess.length ; i++) {
out.writeUTF(mess[i]);
String s = in.readUTF();
System.out.println("客户端收到服务器提问"+s);
Thread.sleep(1000);
}
}catch (Exception e){
System.out.println("服务器已断开");
}finally {
try{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
if(mysocket!=null){
mysocket.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
测试
package socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Address {
public static void main(String[] args) {
InetAddress ip;
try{
ip=InetAddress.getLocalHost();
String localname = ip.getHostName();//本机名
String hostAddress = ip.getHostAddress();//ip地址
System.out.println(localname);
System.out.println(hostAddress);
}catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
-
客户服务器
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
//多线程服务器 期末考试重点
public class SimpleServer {
public static final int SERVERPORT=9999;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
System.out.println("server started");
int number=1;
while(true){
Socket incoming = serverSocket.accept();
System.out.println("Connnection"+number+"accepted:");
new EchoThread(incoming,number).start();
number++;
}
}catch (IOException e){
e.printStackTrace();
}
}
}
class EchoThread extends Thread{
private Socket s;
private int counter;
public EchoThread(Socket i, int c){
s=i;
counter=c;
}
@Override
public void run() {//线程体
try{
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("hello Enter BYE to exit");
while(true){
String line = in.readLine();
if(line.trim().equals("")){ continue;}
if(line.trim().equalsIgnoreCase("BYE")){ break;}
else{
System.out.println("Echo"+counter+":"+line);
out.println("Receive:"+line);
}
}
in.close();
out.close();
s.close();
}catch (Exception e){
System.out.println(e);
}
}
}
-
swing
可能不考
package mySwing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//考试!!
public class TestCopy extends JFrame implements ActionListener {
JButton b_copy,b_clear,b_exit;//按钮
JLabel jb;
JPanel pn,ps;//面板
JTextField jf;//文本框
JTextArea ja;//文本区
TestCopy(){
this.setTitle("testCopy");
this.setSize(400,300);
this.setLocation(100,100);
this.setLayout(new BorderLayout());//分五个区
b_copy= new JButton("Append");
b_clear= new JButton("Clear");
b_exit= new JButton("Exit");
b_copy.addActionListener(this);//按钮事件注册
b_clear.addActionListener(this);
b_exit.addActionListener(this);
ps= new JPanel();
ps.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
ps.add(b_copy);
ps.add(b_clear);
ps.add(b_exit);
this.add(BorderLayout.SOUTH,ps);
jb= new JLabel("input information");
jf= new JTextField(20);
pn =new JPanel();
pn.add(jb);
pn.add(jf);
this.add("North",pn);
ja = new JTextArea(10,40);
ja.setLineWrap(true);
add("Center",ja);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {//事件处理程序
if(e.getActionCommand()=="Append"){
StringBuilder bf = new StringBuilder(ja.getText());
bf.append(jf.getText());
ja.setText(bf.toString());
}else if(e.getActionCommand()=="Clear"){
jf.setText("");
ja.setText("");
}else if(e.getActionCommand()=="Exit"){
System.exit(0);
}
}
public static void main(String[] args) {
new TestCopy();
}
}
-
awt
package mySwing;
import javax.swing.*;
import java.awt.*;
public class FrameJ extends JFrame {
public FrameJ(){
this.setTitle("test");
this.setLayout(null);
this.setBounds(150,200,300,150);
Container c = getContentPane();
JButton a1 = new JButton("按钮1");
JButton a2 = new JButton("按钮2");
a1.setBounds(10,30,80,30);
a2.setBounds(100,30,80,30);
c.add(a1);
c.add(a2);
this.setVisible(true);
}
public static void main(String[] args) {
new FrameJ();
}
}
-
模拟顺序表
package myArray;
import java.util.Scanner;
public class SqList {
int elem[]; //存储一组数据
int length; //顺序表的当前长度
SqList(int n){//构造器,用来初始化顺序表,最大长度为n
elem=new int[n];
length=0;
}
void inputList(int m) { //对顺序表输入m个整数
if(m>elem.length) {
System.out.println(m+"过大!超过数组长度!");
return;
}
System.out.println("请输入"+m+"个整数:");
Scanner reader=new Scanner(System.in);
for(int i=0;i<m;i++)
elem[i]=reader.nextInt();
reader.close();
length=m; //顺序表的当前长度为m
}
void printList() { //输出顺序表中的数据,每5个一换行
System.out.print("数组中的数据为:");
for(int i=0;i<length;i++) {
if(i%5==0) System.out.println();
System.out.print(elem[i]+" ");
}
System.out.println();
}
int minList() {
int min;
min=elem[0];
for(int i=1;i<length;i++)
if(elem[i]<min) min = elem[i];
return min;
}
boolean insertList(int i,int e) {
//在第i个元素前插入一个元素e,插入成功返回true,插入失败返回false
if(i<1 || i>length+1) return false;
if(length>=elem.length) return false;
for(int j=length-1;j>=i-1;j--)
elem[j+1]=elem[j];
elem[i-1]=e;
length++;
return true;
}
boolean deleteList(int i) {
//删除第i个元素,删除成功返回true,删除失败返回false
if(i <= 0 || i > elem.length){
return false;
}
for(int j = i; j < elem.length - 1; j++){
elem[j] = elem[j + 1];
}
length--;
return true;
}
public static void main(String[] args) {// 程序的入口
SqList L=new SqList(100);
L.inputList(5);
L.printList();
System.out.println("顺序表中的最小元素的值为:"+L.minList());
if(L.insertList(3,999)==true)
System.out.println("charuchenggong!");
L.printList();
if(L.deleteList(4)==true)
System.out.println("deletechenggong!");
System.out.println("---删除后---");
L.printList();
}
}
-
StringDemo
package string;
public class DemoString01 {
public static void main(String[] args) {
String str = Integer.toString(456);
String str2 = Integer.toBinaryString(456); // 获取数字的二进制表示
int i=Integer.parseInt("456");
int maxint=Integer.MAX_VALUE;//int最大取值
int intsize=Integer.SIZE;//int的二进制位数
System.out.println("'456'的十进制表示为:" + str);
System.out.println("'456'的二进制表示为:" + str2);
System.out.println("\"456\"转换为十进制为:" + i);
System.out.println("int类型的最大取值为:" + maxint);
System.out.println("int类型的二进制位数为:" + intsize);
}
}
/* '456'的十进制表示为:456
'456'的二进制表示为:111001000
"456"转换为十进制为:456
int类型的最大取值为:2147483647
int类型的二进制位数为:32 */
package string;
public class DemoString01 {
public static void main(String[] args) {
String str=new String("abc def ghi gkl");
String[] newstr=str.split(" "); //对字符串拆分
for(int i=0;i<newstr.length;i++) {
System.out.println(newstr[i]);
}
String[] newstr2=str.split(" ",2);//限定拆分次数
for(int j=0;j<newstr2.length;j++) {
System.out.println(newstr2[j]);
}
}
}
/*abc
def
ghi
gkl
abc
def ghi gkl*/
package string;
public class DemoString01 {
public static void main(String[] args) {
String s1=new String("abc");
String s2=new String("ABC");
String s3=new String("abc");
boolean b=s1.equals(s2);//false
boolean b2=s1.equalsIgnoreCase(s2);//true
System.out.println(s1+"equals"+s2+":"+b);
System.out.println(s1+"equalsIgnoreCase"+s2+":"+b2);
b=(s1==s3); //等号比较的是引用,即地址等不等
System.out.println("s1==s3"+b);//false
String s4="abc";
String s5="abc";
String s6="abcd";
b=(s4==s5);//ture 字符串池
System.out.println("s4==s5"+b);
b=(s5==s6);//false
System.out.println("s5==s6"+b);
}
}
package string;
public class DemoString01 {
public static void main(String[] args) {
String regex="\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
// \\w代表可用标识符的字符但不包括$,*代表0次或多次{n,m}代表出现n至m次
String str1="aaa@";
String str2="aaaaa";
String str3="[email protected]";
if(str1.matches(regex)) {
System.out.println(str1+"是一个合法的email地址格式");
}
if(str2.matches(regex)) {
System.out.println(str2+"是一个合法的email地址格式");
}
if(str3.matches(regex)) {
System.out.println(str3+"是一个合法的email地址");
}
}
}
package string;
//Stringbuilder线程不安全最快了
public class DemoString01 {
public static void main(String[] args) {
String str=new String();
long start= System.currentTimeMillis();
for(int i=0;i<10000;i++) {
str=str+i;
}
long end=System.currentTimeMillis();
System.out.println(end-start);
//使用StringBuffer
StringBuffer sbf=new StringBuffer();
long start2= System.currentTimeMillis();
for(int i=0;i<1000000;i++) {
sbf.append(i);
}
long end2=System.currentTimeMillis();
System.out.println(end2-start2);
//使用StringBuilder
StringBuilder sbd=new StringBuilder();
long start3= System.currentTimeMillis();
for(int i=0;i<1000000;i++) {
sbd.append(i);
}
long end3=System.currentTimeMillis();
System.out.println(end3-start3);
}
}
package chap3;
public class test {
public static int countSubstring(String s,String sub) {
//统计sub在串s中出现的次数
int len=sub.length();
int sum=0;
while(s.indexOf(sub)>=0) {
sum++;
s=s.substring(s.indexOf(sub)+len);
}
return sum;
}
public static void main(String[] args) {
String s="This is a book.";
System.out.println(countSubstring(s,"is"));
}
}
-
面向对象
考试内容:输出题(1)多维数组(1),面向对象(2),文件读写(1),socket(1),多线程(1),swing
package chapter4;
public abstract class Shape {
public abstract double getGirth();
public abstract double getArea() ;
}
package chapter4;
public class Rect extends Shape{
double width;
double height;
public Rect(double width,double height) {
this.height=height;
this.width=width;
}
public Rect() { }
public double getGirth() {
return(width+height)*2;
}
public double getArea() {
return width*height;
}
}
package chapter4;
public class Circle extends Shape{
double r;
final double PI=3.1415;
public Circle(double r) {
this.r=r;
}
public Circle() {}
@Override
public double getGirth() {
// TODO Auto-generated method stub
return 2*PI*r;
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return PI*r*r;
}
}
package chapter4;
public class Square extends Rect{
public Square(double width) {
super(width,width);
}
}
-
断言
package chap5;
import java.util.Scanner;
// 断言
public class AssertEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]=new int[10];
int sum=0;
Scanner r=new Scanner(System.in);
for(int i=0;i<a.length;i++) {
a[i]=r.nextInt();
assert a[i]>=0:"负数不能位成绩"; //条件为真执行
sum+=a[i];
}
r.close();
System.out.println("总成绩为"+sum);
}
}
-
反射
package string;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectFile {
//反射
public static void main(String[] args) {
File file = new File("12.jpg");
Class cs= file.getClass();//得到字节码类
Field[] declaredFields = cs.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
System.out.println(declaredFields[i]);
}
Constructor[] declaredConstructors = cs.getDeclaredConstructors();
for (int i = 0; i < declaredConstructors.length; i++) {
System.out.println(declaredConstructors[i]);
}
Method[] declaredMethods = cs.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
System.out.println(declaredMethods[i]);
}
}
}
-
集合
ArrayList
import java.util.ArrayList;
import java.util.Objects;
/*
java.util
ArrayList<E> E是泛型
ArrayList 常见方法:
public boolean add(E e): 向集合添加元素,参数类型与泛型一值,对于ArrayList 来说add方法都是TRUE的
public E get(int index): 从集合中获取对应下标的元素,返回值就是被删除的元素
public E remove(int index):从集合中删除元素,参数是索引编号,返回值是被删除的元素
public int size():获取集合长度,返回集合长度
*/
public class Demo02ArrayList
{
public static void main(String[] args) {
// ArrayList<String> arr = new ArrayList<>();//jdk1.7+开始右侧<>内容可省略,但是<>本身不能省略
// System.out.println(arr);//对于ArrayLists对象来说arr不是地址值,如果为空输出[];
// arr.add("江西省");
// arr.add("江东省");
// System.out.println(arr);//[江西省, 江东省]
ArrayList<Integer> In = new ArrayList<>();
In.add(2);
In.add(3);
In.add(1);
In.add(5);
In.add(6);
System.out.println(In.size());
System.out.println(In);
System.out.println(In.get(2));
In.remove(2);
//将ArrayList转化为数组
Object[] objects = In.toArray();
for (int i = 0; i < objects.length; i++) {
System.out.println((int)objects[i]);
}
System.out.println(In);
}
}
LinkedList
import java.util.LinkedList;
//LinkedList是List的实现类
/*
特点:底层链表,查询慢,插入快
包含大量插入删除首位方法
*/
public class Demo02LinkedList {
public static void main(String[] args) {
LinkedList<Integer> link = new LinkedList<>();
link.addFirst(1);
link.addFirst(2);
link.addFirst(3);
System.out.println(link);
link.add(3,12);
System.out.println(link);
link.addLast(5);
System.out.println(link);
Integer it= link.get(2);
System.out.println(it);
Integer getFirst = link.getFirst();
System.out.println(getFirst);
// link.clear();
// System.out.println(link);
// link.getFirst();删除了list元素,在删除会报错
System.out.println("--------------");
Integer fir = link.removeFirst();
System.out.println(fir);
System.out.println(link);
}
}
Set
package cn.itcast.demo04Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
java.util.set接口继承collection接口
set接口的特点:
1.不允许存储重复的元素
2.没有索引,没有带索引的方法也不能使用普通for循环遍历
有两个实现类 HashSet集合实现了set接口
3.自身是无序的集合,存储元素和取出元素顺序可能不一致
4.查询速度非常快
哈希值:是一个十进制整数,由系统随机给出(就是对象地址,是一个逻辑地址,是模拟出来的地址,不是数据实际存储的物理地址)
在object类有一个方法,可以获取对象的hash值
set元素不重复原理,首先判断加入元素的hashcode值,
根据hash值存入数组,如果有相同用并p1.equals(p2)判断两个字符串比较,不同才用链表存储,
*/
public class Demo01Set {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
// Iterator<Integer> it = set.iterator(); 在未插入数据前就获取迭代器没输出
set.add(1);
set.add(6);
set.add(1);
set.add(2);
set.add(4);
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
// System.out.println(set);
}
}
HashSet
package chapter5;
import java.util.HashSet;
import java.util.Iterator;
public class SetProcess {
public static void main(String[] args) {
HashSet<Integer> A=new HashSet<Integer>();//使用泛型
HashSet<Integer> B=new HashSet<Integer>();
for(int i=1;i<=4;i++) A.add(i);//[1,2,3,4]
B.add(1);B.add(2);B.add(5);B.add(6);
@SuppressWarnings("unchecked")//b=[1,2,5,6]
HashSet<Integer> tempset=(HashSet<Integer>)A.clone();
A.removeAll(B);//A=A-B
B.removeAll(tempset);//B=B-A
B.addAll(A);//做并集,去掉交集
System.out.println("A和B的对称差的集合有"+B.size()+"个元素");
Iterator<Integer> iter=B.iterator();
while(iter.hasNext()) {
System.out.printf("%d",iter.next());
}
}
}
TreeSet
package chapter5;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
public class SetDemo {
public static void main(String[] args) {
HashSet s=new HashSet();
s.add("one");
s.add("two");
s.add(new Integer(3));
s.add(new Float(4.0F));
s.add("two");
s.add(new Integer(3));
System.out.println(s);
System.out.println("------------------------");
Iterator it =s.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("hashset的长度"+s.size());
HashSet<String> ss=new HashSet<>();
ss.add("one");
ss.add("one");
for(String t:ss)
System.out.println(t.toUpperCase()+" ");
TreeSet tree=new TreeSet();
tree.add("one");
tree.add("two");
tree.add(new Integer(3).toString());
tree.add(new Float(4.0F).toString());
tree.add("two");
tree.add(new Integer(3).toString());
System.out.println(tree);
}
}
HashMap
package review.collections;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
//面向对象的方法求出数组中重复 value 的个数,按如下个数输出
HashMap<Integer,Integer> arrtimes = new HashMap<>();
int arr[] ={1,4,1,4,2,5,4,5,8,7,8,77,88,5,4,9,6,2,4,1,5};
//初始化,给每个value赋为0
for (int i = 0; i <arr.length ; i++) {
arrtimes.put(arr[i],0);
}
//遍历arrtimes
for (Map.Entry<Integer,Integer> arrtime:arrtimes.entrySet()) {
System.out.println(arrtime.getKey()+":"+arrtime.getValue());
}
for (int i = 0; i <arr.length ; i++) {
if(arrtimes.containsKey(arr[i])){
Integer integer = arrtimes.get(arr[i]);//获取对应key的value
integer++;
arrtimes.put(arr[i],integer);
}
}
for (Map.Entry<Integer,Integer> arrtime:arrtimes.entrySet()) {
System.out.println(arrtime.getKey()+":"+arrtime.getValue());
}
}
}
import java.io.*;
import java.util.HashMap;
import java.util.Set;
public class StringSplitFromTXT {
//从txt文件中读取分割字符
public static void main(String[] args) {
File fileread = new File("english.txt");
File filewrite = new File("englishct.txt");
try {
Writer writer = new FileWriter(filewrite);//读取输出流
Reader reader = new FileReader(fileread);//输入流
BufferedReader bufferedReader = new BufferedReader(reader);//把输入流放入BufferedReader好处理
BufferedWriter bufferedWriter = new BufferedWriter(writer);
String str;
HashMap<String,Integer> hashMap = new HashMap<>();
while((str=bufferedReader.readLine())!=null){//每次读取一行并赋值给str
String[] splits = str.split("\\s+");//空格分隔,正则表达式匹配多个字符
for (String split : splits) {
// System.out.println(split);
if(hashMap.get(split)!=null){
Integer integer = hashMap.get(split);//这里的value没有赋值到value中
integer++;
hashMap.replace(split,integer);
}else{
hashMap.put(split,1);
}
}
bufferedWriter.write(str);
bufferedWriter.flush();
}
str=null;
Set<String> strings = hashMap.keySet();//获取键数组
for (String string : strings) {
str=string+"次数"+hashMap.get(string);
System.out.println(str);
bufferedWriter.write(str);
bufferedWriter.flush();
}
writer.close();
reader.close();
bufferedReader.close();
bufferedWriter.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
Collections
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
/*
题目:
生成6个1-33之间的随机整数,添加到集合,并遍历
思路:
1.需要存储6个数字,创建一个集合,<Integer>
2.产生随机数,用到Random
3.循环6次
4.
*/
public class Demo01ArrayListRandom {
/**
* @Description: 复习
* @Param:
* @return:
* @Author: soup
* @Date: 2022/5/26 10:09
*/
public static void main(String[] args) {
ArrayList<Integer> arrs = new ArrayList<>();
Random r = new Random();
for (int i = 0; i <6 ; i++) {
arrs.add(r.nextInt(33)+1);
}
Collections.sort(arrs, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
// int i = Collections.binarySearch(arrs, 32);
System.out.println(arrs.toString());
Collections.rotate(arrs,4);//右移呗
// System.out.println(i);
System.out.println(arrs.toString());
// String s="a";
ArrayList<String> arrayList = new ArrayList<>(5);
Collections.addAll(arrayList,"soup","tang","man","hah","good");//添加任意数量的字符串
Collections.fill(arrayList,new String("he"));
System.out.println(arrayList);//输出是[],fill是替换不能初始化替换,就是原来没有的不能
}
// public static void main(String[] args) {
// ArrayList<Integer> In = new ArrayList<>();
// Random r = new Random();
// for (int i = 0; i < 6; i++) {
// int num=r.nextInt(33)+1;//该方法随机生成[0,n)区间范围数
// In.add(num);
// }
// System.out.println(In);
// }
}
-
文件操作
字节流
package FileRead;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//字节输入流
public class FileInput {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("1.txt");
byte a[] = new byte[3];//创建三个字符数组
//遍历
while(fileInputStream.read(a)!=-1){
System.out.println(new String(a));
}
int read = fileInputStream.read();
System.out.println((char)read);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("测试是否执行到此finally");
fileInputStream.close();
}
System.out.println("测试是否执行到此");
}
}
package FileRead;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//字节输出流
public class FileOut {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("x.txt", true);//原有基础上append追加每次
fileOutputStream.write("soup".getBytes());
fileOutputStream.write("mman".getBytes(),1,2);//写入ma
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("测试发生异常能否执行到此finally");
fileOutputStream.close();
}
System.out.println("测试发生异常能否执行到此");
}
}
package FileRead;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//文件拷贝
public class FileCopy {
public static void main(String[] args) {
FileInputStream fileInputStream=null; //从硬盘中读入cpu
FileOutputStream fileOutputStream =null;//写出文件
try{
fileInputStream = new FileInputStream("ErrorlogCopy.txt");
fileOutputStream = new FileOutputStream("ErrorlogCopy2.txt");
byte b[] = new byte[3];
while(fileInputStream.read(b)!=-1){
fileOutputStream.write(b);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("测试使用时间");
}
}
}
文件读写并序列化对象
package FileRead;
import java.io.Serializable;
class Customer implements Serializable {//注意实现类Serializable
private String name;
private int age;
private double money;
private transient String password;
public Customer() {}
public Customer(String name, int age, String password, double money) {
this.name = name;
this.age = age;
this.password = password;
this.money = money;
}
public String getName() {return name;}
public void setName(String name) {
this.name = name;
}
public int getAge() {return age;}
public void setAge(int age) {
this.age = age;
}
public double getMoney() {return money;}
public void setMoney(double money) {
this.money = money;
}
public String getPassword() {return password;}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "name=" + name + " age=" + age
+ " password=" + password
+ " money=" + money;
}
}
package FileRead;
import java.io.*;
public class SerilizationTest {
public static void main(String[] args) throws IOException {
FileOutputStream fos = null;
ObjectOutputStream oos =null;
try {
Customer customer = new Customer("Dingdang", 10, "kangfu", 200.0);
// Customer customer2 = new Customer("Dingdang", 10, "kangfu", 200.0);
fos = new FileOutputStream("customer.txt");
oos = new ObjectOutputStream(fos);//套接
System.out.println(customer);
// System.out.println(customer2);
System.out.println("序列化");
oos.writeObject(customer);
// oos.writeObject(customer2);
oos.flush();
}catch (Exception e){
e.getMessage();
}
finally {
oos.close();
fos.close();
}
FileInputStream fis = null;
ObjectInputStream ois =null;
try{
fis = new FileInputStream("customer.txt");
ois = new ObjectInputStream(fis);
System.out.println("对象反序列化");
Customer c1 = (Customer) ois.readObject();
System.out.println(c1);
// Customer c2 = (Customer) ois.readObject();
// System.out.println(c2);
}catch (Exception e){
e.getMessage();
}
finally {
ois.close();
fis.close();
}
}
}
字符流
package FileRead;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReadTest {
public static void main(String[] args) throws IOException {
FileReader fileReader=null;
// int read = fileReader.read("ErrorlogCopy.txt");
try {
fileReader = new FileReader("ErrorlogCopy.txt");
char c[] = new char[3];
// String s = new String();
while(fileReader.read(c)!=-1){
System.out.println(c);
c=new char[3];
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
fileReader.close();
}
}
}
package FileRead;
import java.io.*;
//buffer缓冲区流
public class EnglishTest {
public static void main(String[] args) {
File fRead = new File("english.txt");
File fWrite = new File("englishCount.txt");
try{
//BufferedWriter是Writer子类
Writer out = new FileWriter(fWrite);
BufferedWriter bufferedWriter = new BufferedWriter(out);
Reader fileReader = new FileReader(fRead);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String str=null;
while((str=bufferedReader.readLine())!=null){
String[] split = str.split("\\s+");
int length = split.length;
str=str+"字数"+length;
bufferedWriter.write(str);
bufferedWriter.newLine();
}
bufferedWriter.close();
out.close();
bufferedReader.close();
fileReader.close();
System.out.println("统计完毕 放在EnglishCount.txt");
}catch(IOException e){
e.getMessage();
}
}
}
-
服务器tcp
package filetcp;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileUpload_Server {
public static void main(String[] args) throws IOException {
System.out.println("服务器启动中.....");
//设置服务器端口号
ServerSocket serverSocket = new ServerSocket(6666);
//建立连接
Socket socket = serverSocket.accept();
//创建输入流
BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
//创建输出流放入本地
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("copy.jpg"));
//读写数据
byte b[] =new byte[1024];
int len;
while((len=bufferedInputStream.read(b))!=-1){
bufferedOutputStream.write(b,0,len);
}
bufferedOutputStream.close();
bufferedInputStream.close();
serverSocket.close();
System.out.println("文件已经上传");
}
}
package filetcp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class FileUPload_Client {
public static void main(String[] args) throws IOException {
//创立连接
Socket socket = new Socket("localhost",6666);
//读入输入流
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("12.jpg"));
//创建输出流,写到服务器
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
byte b[]=new byte[1024];//每次把输入流b大小的数据送到输出流
int len;
while((len=bufferedInputStream.read(b))!=-1){
bufferedOutputStream.write(b,0,len);
bufferedOutputStream.flush();
}
System.out.println("文件发送完毕");
bufferedInputStream.close();
bufferedOutputStream.close();
socket.close();
}
}
-
线程
public class Tickets {
//票数
int ticketNum;
public Tickets(int ticketNum) {
this.ticketNum = ticketNum;
}
public void saleTicket(){
synchronized (this){
if (ticketNum>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"在卖第"+ticketNum+"票");
ticketNum--;
}
}
}
}
public class RunnableTicketTest implements Runnable{
Tickets tickets = new Tickets(50);
@Override
public void run() {
while(true){
if(tickets.ticketNum>0){
tickets.saleTicket();
}else {
System.out.println(Thread.currentThread() + "this is no tickets");
break;
}
}
}
}
public class TicketsTest {
public static void main(String[] args) {
RunnableTicketTest runnableTicketTest = new RunnableTicketTest();
Thread t1 = new Thread(runnableTicketTest);
Thread t2 = new Thread(runnableTicketTest);
t1.start();
t2.start();
}
;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
public class Accout {
private double balance;
public Accout(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
//取钱
public synchronized void draw(double money){
while(balance<money){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
balance-=money;
System.out.println(Thread.currentThread().getName()+"取了"+money+"还剩"+balance+"元");
}
//存钱
public synchronized void deposit(double money){
System.out.println(Thread.currentThread().getName()+"存了"+money+"还有"+balance+"元");
balance+=money;
try{
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}
public class DepositThread extends Thread {
private Accout accout;
private double depositMoney;
public DepositThread(Accout accout, double depositMoney) {
this.accout = accout;
this.depositMoney = depositMoney;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
accout.deposit(depositMoney);
}
}
}
public class DrawThread extends Thread {
private Accout accout;
private double drawMoney;
//用构造的方法获取账户余额
public DrawThread(Accout accout, double drawMoney) {
this.accout = accout;
this.drawMoney = drawMoney;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
accout.draw(drawMoney);
}
}
}
package cn.itcast.bankExample;
public class BankTest {
public static void main(String[] args) {
Accout accout = new Accout(100);
Thread t1 = new DrawThread(accout,200);
Thread t2 = new DepositThread(accout,200);
t1.start();
t2.start();
}
}