一、java入门随便写写:
1.判断一个数是不是素数:
代码如下:
import java.util.Scanner;
public class sushu {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个整数:");
int n=scan.nextInt();
boolean isprime = true;
for(int i=2;i<=Math.sqrt(n);i++) {
if(n%i==0) {
isprime = false;
break;
}
}
if(isprime)
System.out.println(n+"是一个素数");
else
System.out.println(n+"不是一个素数");
}
}
结果:
2.素数判断升级:
代码如下:
public class sushupanduan {
public static void main(String[] args) {
int m = 100;
int n = 200;
int count = 0;
for(int i=m;i<n;i++){
if(isPrime(i)){
count++;
System.out.print(i+" ");
if(count%10==0){
System.out.println();
}
}
}
System.out.println();
System.out.println("在"+m+"和"+n+"之间共有"+count+"个素数");
}
public static boolean isPrime(int n){
boolean sushu = true;
if(n==1)
sushu = false;
else{
for(int i=2;i<=Math.sqrt(n);i++){
if((n%i)==0){
sushu = false;
break;
}
else
sushu = true;
}
}
return sushu;
}
}
结果:
3.一个数出现的次数:
代码如下:
public class cishu {
public static void main(String[] args) {
int count = 0;
for (int i = 400; i <= 499; i++) {
int ge = i%10;
int shi = (i/10)%10;
int bai = (i/100)%10;
if(ge==4) {
count += 1;}
if(shi==4) {
count += 1;}
if(bai==4) {
count += 1;
}
}
System.out.println();
System.out.println("4一共出现的次数是:" + count + "次");
}
}
结果:
4.统计一个数组中某个数字的个数:
代码如下:
import java.util.Scanner;
public class shuzutongji {
public static void main(String[] args) {
int [] a= {120,422,546,565,13,643,868};
int count = 0;
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个数:");
int d=scan.nextInt();
for(int i=0;i<a.length;i++) {
int n=a[i];
while(n!=0) {
int r=n%10;
if(r==d)
count++;
n=n/10;
}
}
System.out.println(d+"的个数为:"+count);
}
}
结果:
5.回文数:
代码如下:
//任何一个数除以10的余数就是该数最后一位
//任何一个数除以10的商就是排除掉最后一位后的数
//所以 ,一个数1234 就可以通过这种方法得到 123 和 4
//接下来对 123 进行同样的操作,就得到 12 和 3
//接下来得到 1 和 2
//接下来得到 0 和 1
//整个过程是个循环,当商不是 0 的时候就一直这么干
//每次拿到一个余数,都用来构造新数,新数=新数*10+余数
//所以经过四次循环后,我们得到新数 4321 ,如果是回文,那么新数应该等于原数,否则,说明不是回文。
import java.util.Scanner;
public class huiwen {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入一个整数:");
int hw=scan.nextInt();
int y=0;
int h=hw;
while(hw>0){
y=y*10+hw%10;
hw=hw/10;
}
if(y==h){
System.out.println("是回文数");
}else{
System.out.println("不是回文数");
}
}
}
结果:
6.冒泡法排序:
代码如下:
public class maopaofa {
public static void main(String[] args) {
int a[] = {23,43,75,1,456,78,678,80,789,55};
System.out.println("排序前的数组:");
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+" ");
}
System.out.println();
for(int i=0;i<a.length;i++) {
for(int j=0;j<a.length-i-1;j++) {
int t=a[j];
if(a[j]>a[j+1]) {
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println("排序后的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
结果:
注:冒泡排序算法的原理如下:
1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2.对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3.针对所有的元素重复以上的步骤,除了最后一个。
4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
7.杨辉三角:
代码如下:
//杨辉三角
public class yanghuisanjiao {
public static void main(String[] args) {
int row=8;
int array[][]=new int[row][];
for(int i=0;i<row;i++) {
array[i]=new int[i+1];
array[i][0]=1;
array[i][i]=1;
}
for(int i=2;i<row;i++) {
for(int j=1;j<i;j++) {
array[i][j]=array[i-1][j-1]+array[i-1][j];
}
}
for(int i=0;i<row;i++) {
for(int j=0;j<=i;j++) {
System.out.print(array[i][j]+"\t");
}
System.out.println();
}
}
}
结果:
注:杨辉三角的斜边都是数字1组成,其余的数则等于它肩上的两个数之和
8.使用对象,构造方法求圆的面积和周长:
代码如下:
import java.util.Scanner;
public class Circle {
private double r;
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public Circle(double r) {
this.r=r;
}
public void output() {
System.out.println("圆的半径:"+r);
System.out.println("圆的面积:"+area());
System.out.println("圆的周长"+perimeter());
}
public double area() {
return 3.14*r*r;
}
public double perimeter() {
return 2*3.14*r;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入圆的半径:");
double r=scanner.nextDouble();
Circle circle=new Circle(r);
circle.output();
}
}
数组拷贝的三种方法:
1.使用循环语句:
public class cope {
public static void main(String[] args) {
int[]array1 = {1,2,3,4,5};
int[]array2 = new int[array1.length];
for(int i=0;i<array1.length;i++) {
array2[i] = array1[i];
}
for(int i=0;i<array2.length;i++) {
System.out.print(array2[i]+",");
}
}
}
2.使用clone()方法:
public class clone {
public static void main(String[] args) {
int[] array1= {1,2,3,4,5};
int[] array2 = array1.clone();
for(int i=0;i<array1.length;i++)
System.out.print(array2[i]+",");
}
}
3.使用Ststem.arraycopy()方法:
public class arraycope {
public static void main(String[] args) {
int[] array1 = {1,2,3,4,5};
int[] array2 = new int[10];
System.arraycopy(array1,0,array2,0,array1.length) ;
for(int i=0;i<array1.length;i++)
System.out.print(array2[i]+",");
}
}
注:二维数组可以用来解决矩阵问题。
参数传递
1.值传递:
public class CallByValue {
public static void main(String[] args) {
int num=5;
System.out.println("调用change方法前:"+num);
CallByValue callByValue= new CallByValue();
callByValue.change(num);
System.out.println("调用后change方法后"+num);
}
public void change(int num) {
num+=5;
System.out.println("change方法中num的值为:"+num);
}
}
2.引用传递:
public class CallByRef {
int a,b;
CallByRef(int i,int j){
a=i;
b=j;
}
void change(CallByRef obj) {
obj.a=50;
obj.b=40;
System.out.println("在change方法中 obj.a="+obj.a+",obj.b="+obj.b);
}
public static void main(String[] args) {
CallByRef obj=new CallByRef(15,20);
System.out.println("在change方法前 obj.a="+obj.a+",obj.b="+obj.b);
obj.change(obj);
System.out.println("在change方法后 obj.a="+obj.a+",obj.b="+obj.b);
}
}
obj 在change()前后的内存状态发生了变化,因为被传递的值是一个对象,main()中的obj和change中的obj都指向了同一个内存空间。
计算两点之间距离:
import java.util.Scanner;
public class Point {
private double x=0;
private double y=0;
public Point(double x,double y) {
this.x=x;
this.y=y;
}
public double distance(Point p1,Point p2) {
double dx=p1.x-p2.x;
double dy=p1.y-p2.y;
return (Math.sqrt(dx*dx+dy*dy));
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入第一个点:");
double x=sc.nextDouble();
double y=sc.nextDouble();
Point p1=new Point(x,y);
System.out.println("请输入第二个点:");
double a=sc.nextDouble();
double b=sc.nextDouble();
Point p2=new Point(a,b);
System.out.println("两点之间距离:"+p1.distance(p1, p2));
}
}
继承中构造函数的调用顺序:
public class Base {
protected int a;
public Base() {
a=20;
System.out.println("In Base constructor!");
}
public static void main(String[] args) {
Son obj=new Son();
obj.print();
}
}
class Son extends Base{
int b;
public Son(){
b=100;
System.out.println("In Son constructor!");
}
public void print() {
System.out.println("a="+a+",b="+b);
}
}
结论:
几种查找方法:
顺序查找:
package c001;
import java.util.Scanner;
public class Shunxuchazhao {
public static void main(String[] args) {
int i=0;
Scanner sc=new Scanner(System.in);
System.out.println("请输入要查找的数:");
int k=sc.nextInt();
int[]a={1,3,4,2,6,7,9,34,87,24,12,65};
while(i<a.length && a[i]!=k)
i++;
if(i>=a.length)
System.out.println("未找到!");
else
System.out.println("查找的元素位于:"+(i+1));
}
}
结果:
折半查找
package c001;
import java.util.Scanner;
public class Zhebanchazhao {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入要查找的数:");
int[]a={1,2,3,5,7,12,34,56,89,144,567};
int k=sc.nextInt();
int i=0;
int low=0;
int high=a.length-1;
int mid;
while(low<=high) {
mid=(low+high)/2;
if(k==a[mid])
System.out.println("查找的元素位于"+(mid+1));
if(k<a[mid])
high=mid-1;
else
low=mid+1;
}
}
}
结果:
折半查找的递归方法:
package c001;
import java.util.Scanner;
public class Diguizheban {
private static int diguizheban(int a[],int k,int low,int high ) {
if (low>high) {
System.out.println("无法查找到该元素!");
return -1;
}
else {
int mid=(low+high)/2;
if (k==a[mid]) {
System.out.println("查找元素为"+a[mid]+";"+"在"+mid+"位置");
return mid;
}
else {
if (k<a[mid]) {
return diguizheban(a, k, low, mid-1);
}
else {
return diguizheban(a, k, mid+1, high);
}
}
}
}
public static void main(String[] args) {
int a[]={1,2,3,5,7,12,34,56,89,144,567};
Scanner sc=new Scanner(System.in);
System.out.println("请输入要查找的数:");
int k=sc.nextInt();
System.out.println("递归算法:");
diguizheban(a, k, 0, a.length-1);
}
}
直接插入排序:
package c001;
import java.util.Scanner;
public class Zhijiecharupaixu {
public static void Zhijiecharupaixu(int[] a) {
int tmp;
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0; j--) {
if (a[j] < a[j - 1]) {
tmp = a[j - 1];
a[j - 1] = a[j];
a[j] = tmp;
}
}
}
}
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
System.out.println("排序前的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
Zhijiecharupaixu(a);
System.out.println("排序后的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i] + " ");
}
}
折半插入排序:
package c001;
public class Zhebancharupaixu {
public static void Zhebancharupaixu(int[] a) {
int i,j,low,high,mid,tmp;
for(i=1;i<a.length;i++) {
if(a[i]<a[i-1]) {
tmp=a[i];
low=0;
high=i-1;
while(low<=high) {
mid=(low+high)/2;
if(tmp<a[mid])
high=mid-1;
else
low=mid+1;
}
for(j=i-1;j>=high+1;j--)
a[j+1]=a[j];
a[high+1]=tmp;
}
}
}
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
System.out.println("排序前的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
Zhebancharupaixu(a);
System.out.println("排序后的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
}
希尔排序
package c001;
public class Xierpaixu {
public static void Zhebancharupaixu(int[] a) {
int i,j,d;
int tmp;
d=a.length/2;
while(d>0) {
for(i=d;i<a.length;i++) {
tmp=a[i];
j=i-d;
while(j>=0 && tmp<a[j]) {
a[j+d]=a[j];
j=j-d;
}
a[j+d]=tmp;
}
d=d/2;
}
}
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
System.out.println("排序前的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
Zhebancharupaixu(a);
System.out.println("排序后的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i] + " ");
}
}
冒泡排序:
package c001;
public class Maopaopaixu {
public static void Maopaopaixu(int[] a) {
int i,j;
for( i=0;i<a.length;i++) {
for( j=0;j<a.length-i-1;j++) {
int t=a[j];
if(a[j]>a[j+1]) {
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
public static void main(String[] args) {
int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
System.out.println("排序前的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
Maopaopaixu(a);
System.out.println("排序后的数组:");
for(int i=0;i<a.length;i++)
System.out.print(a[i] + " ");
}
}
快速排序:(由冒泡法改进) 在待排序的n个元素中任取一个元素(一般是第一个),把该元素放在适当位置,数组被分为两部分,所有关键字比该元素小的元素放在前一部分,比它大的放在后一部分,称为一趟划分,然后对产生的两部分分别重复上述操作,直至每一个部分都只有一个元素为空。简而言之:每趟使表的第一个元素放入适当位置,将表一分为二,对子表按递归的方式继续这种划分,直至划分的子表长度为1或0。
在这里插入代码片
抽象类
先建立一个抽象类:
package c002;
public abstract class Shape {
double dim;
public Shape() {
this.dim=dim;
}
public abstract double area();
public abstract double perimeter();
}
建立一个圆类:
package c002;
public class Circle extends Shape{
double rad;
public Circle(double rad) {
this.rad=rad;
}
public double area() {
return Math.PI*rad*rad;
}
public double perimeter() {
return Math.PI*2*rad;
}
}
建立一个正方形类:
package c002;
public class Ractet extends Shape{
double length;
double width;
public Ractet(double length,double width) {
super();
this.width=width;
}
public double area() {
return length*width;
}
public double perimeter() {
return 2*(length+width);
}
}
建立一个测试类用来测试:
package c002;
public class Test {
public static void main(String[] args) {
Shape s=new Circle(10);
Shape s1;
s1=new Ractet(3,4);
System.out.println("圆的面积:"+s.area());
System.out.println("正方形的周长:"+s1.perimeter());
}
}
使用字符界面实现菜单程序,通过接收不同的参数值来打印不同的操作名称
package c003;
import java.util.Scanner;
public class hhhh {
public static void main(String[] args) {
int num= 0;
System.out.println("请输入1~3选择菜单项:");
do {
System.out.println("1.新建");
System.out.println("2.打开");
System.out.println("3.退出");
Scanner input = new Scanner(System.in);
num = input.nextInt();
switch(num) {
case 1:
System.out.println("您选择了新建:");
break;
case 2:
System.out.println("您选择了打开:");
break;
case 3:
System.out.println("您选择了退出,退出!");
break;
default:
System.out.println("无效操作,请重新输入!");
}
}while (num!=3);
}
}
Math类的常见数学运算方法
rint()返回最接近参数的整数,5舍6入
toDegrees() 方法用于将参数转化为角度。
toRadians() 方法用于将角度转换为弧度。
演示代码:
package c003;
public class Mathtest {
public static void main(String[] args) {
System.out.println("Math.E="+Math.E);
System.out.println("Math.PI="+Math.PI);
System.out.println("Math.abs(-1)="+Math.abs(-1));
System.out.println("Math.ceil(2.3)="+Math.ceil(2.3));
System.out.println("Math.floor(2.3)="+Math.floor(2.3));
System.out.println("Math.round(2.3)="+Math.round(2.3));
System.out.println("Math.rint(2.5)="+Math.rint(2.5));
System.out.println("Math.max(2.3,3.2)="+Math.max(2.3,3.2));
System.out.println("Math.min(2.3,3.2)="+Math.min(2.3,3.2));
System.out.println("Math.sin(Math.PI/2)="+Math.sin(Math.PI/2));
System.out.println("Math.cos(Math.PI/2)="+Math.cos(Math.PI/2));
System.out.println("Math.tan(Math.PI/4)="+Math.tan(Math.PI/2));
System.out.println("Math.atan(Math.PI/4)="+Math.atan(Math.PI/4));
System.out.println("Math.toDegrees(Math.PI/4)="+Math.toDegrees(Math.PI/4));
System.out.println("Math.toRadians(45)="+Math.toRadians(45));
System.out.println("Math.sqrt(9)="+Math.sqrt(9));
System.out.println("Math.pow(3,2)="+Math.pow(3,2));
System.out.println("Math.log10(100)="+Math.log10(100));
System.out.println("(int)(Math.random()*10)="+(int)(Math.random()*10));
}
}
Arrays类
binarySearch方法
package c003;
import java.util.*;
public class ArraysSearch {
public static void main(String[] args) {
int[] a= {1,2,3,4,5};
System.out.println("请输入搜索值:");
Scanner scanner=new Scanner(System.in);
int k=scanner.nextInt();
int find=-1;
if((find=Arrays.binarySearch(a,k))>-1) {
System.out.println("找到要搜索的值在"+find+"位置");
}
else {
System.out.println("找不到");
}
}
}
Random类
相同种子数的Random对象,相同次数生成的随机数字是完全相同的。
使用Random类编写一个程序,把1-100中20个不重复的数放入数组中
package c003;
import java.util.Random;
public class Rondomlei {
public static void main(String[] args) {
Random random = new Random();
int a[] = new int[20];
int j=0;
for(int i=0;i<a.length;i++) {
int r=random.nextInt(100);
a[i]=r;
for(j=0;j<i;j++) {
if(a[j]==a[i]) {
i--;
break;
}
}
}
for(int i=0;i<a.length;i++) {
System.out.print(a[i]+" ");
}
}
}
接口
类似于抽象类此处不加以代码解释,接口也可多继承
异常处理
emmmm感觉不重要
例:一个三角形类异常
先创建一个TriangleException类
package ch006;
public class TriangleException extends Exception{
public TriangleException() {
super();
// TODO Auto-generated constructor stub
}
public TriangleException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public TriangleException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public TriangleException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
再创建一个三角形类
package ch006;
public class Triangle {
private double a;
private double b;
private double c;
public Triangle() {}
public Triangle(double a,double b,double c) throws TriangleException{
if(a+b>c && a+c>b && b+c>a) {
this.a=a;
this.b=b;
this.c=c;
}else {
throw new TriangleException("不能构成三角形!");
}
}
public double perimeter() {
return a+b+c;
}
public double area() {
double p=(a+b+c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
}
最后创建一个测试类
package ch006;
public class TriangleRExceptionTest {
public static void main(String[] args) {
try {
Triangle t=new Triangle(13,4,5);
System.out.println(t.area());
System.out.println(t.perimeter());
}catch(TriangleException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
泛型和集合
通过演示不使用泛型和使用泛型实现参数的实例化来认识泛型
不使用泛型
package ch007;
public class NoGeneric {
private Object ob;
public NoGeneric(Object ob) {
this.ob=ob;
}
public Object getOb() {
return ob;
}
public void setOb(Object ob) {
this.ob = ob;
}
public void showType() {
System.out.println("实际类型是:"+ob.getClass().getName());
}
}
package ch007;
public class NoGenericDome {
public static void main(String[] args) {
NoGeneric intOb=new NoGeneric(new Integer(88));
intOb.showType();
int i=(Integer)intOb.getOb();
System.out.println("value="+i);
System.out.println("-------------------------------------");
NoGeneric strOb=new NoGeneric("Hello zjc!");
strOb.showType();
String s=(String)strOb.getOb();
System.out.println("value="+s);
}
}
使用泛型
package ch007;
public class Generic<T> {
private T ob;
public Generic(T ob) {
this.ob=ob;
}
public T getOb() {
return ob;
}
public void setOb(T ob) {
this.ob = ob;
}
public void showType() {
System.out.println("实际类型是:"+ob.getClass().getName());
}
}
package ch007;
public class GenericDome {
public static void main(String[] args) {
Generic<Integer>intOb=new Generic<Integer>(88);
intOb.showType();
int i=intOb.getOb();
System.out.println("value="+i);
System.out.println("----------------------------------");
Generic<String>strOb=new Generic<String>("Hello zjc!");
strOb.showType();
String s=strOb.getOb();
System.out.println("value="+s);
System.out.println("----------------------------------");
Generic<Boolean>boolOb=new Generic<Boolean>(true);
boolOb.showType();
Boolean b=boolOb.getOb();
System.out.println("value="+b);
System.out.println("----------------------------------");
Generic<Byte>byteOb=new Generic<Byte>((byte) 88);
byteOb.showType();
Byte b1=byteOb.getOb();
System.out.println("value="+b1);
System.out.println("----------------------------------");
Generic<Short>shortOb=new Generic<Short>((short) 88);
shortOb.showType();
short s1=shortOb.getOb();
System.out.println("value="+s1);
System.out.println("----------------------------------");
Generic<Long>longOb=new Generic<Long>(88L);
longOb.showType();
long l=intOb.getOb();
System.out.println("value="+l);
System.out.println("----------------------------------");
Generic<Float>floatOb=new Generic<Float>(88F);
floatOb.showType();
float f=floatOb.getOb();
System.out.println("value="+f);
System.out.println("----------------------------------");
Generic<Double>doubleOb=new Generic<Double>(88D);
doubleOb.showType();
double d=doubleOb.getOb();
System.out.println("value="+d);
System.out.println("----------------------------------");
}
}
通配符
使用通配符:
package ch007;
public class WildcarDemo {
public static void func(Generic<?>g) {
}
public static void main(String[] args) {
Generic<Object>obj = new Generic<Object>(12);
func(obj);
Generic<Integer>g = new Generic<Integer>(12);
func(g);
}
}
还可以通过extends关键字限定通配符的界定的类型参数范围
集合类
一个小例子
将20个两位随机数存入arraylist类
方法1:
package ch007;
import java.util.*;
public class ArrayListRandom {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(20);
Random random = new Random();
for(int i=0;i<20;i++) {
int x=random.nextInt(89)+10;
if(arr.indexOf(x)!=-1) {
i--;
continue;
}
arr.add(x);
}
System.out.println(arr);
}
}
方法2:
package ch007;
import java.util.*;
public class ArrayListRandom {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(20);
int x;
Random random = new Random();
for(int i=0;i<20;i++) {
do {
x=random.nextInt(89)+10;
}while(arr.indexOf(x)>=0);
arr.add(x);
}
System.out.println(arr);
}
}
如果想存入20个两位的偶数
把x=random.nextInt(89)+10换成x=2*(random.nextInt(44)+5)
Set接口
Set接口继承Collection接口不允许有重复项
一个小例子:输出学生信息
package ch007;
import java.util.*;
public class Student implements Comparable<Student>{
private String id;
private String name;
private int score;
public Student(String id, String name, int score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", score=" + score + "]";
}
@Override
public int compareTo(Student o) {
return (this.score-o.score);
}
}
如果想按照姓名排序
package ch007;
import java.util.*;
public class StudentDemo {
public static void main(String[] args) {
TreeSet<Student> hs = new TreeSet<Student>();
hs.add(new Student("2017001","Tom",60));
hs.add(new Student("2017002","Jack",70));
hs.add(new Student("2017003","Rose",80));
System.out.println(hs);
for(Student s:hs) {
System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getScore());
}
}
}
给定任意长度的字符串,找出其出现次数最多的字符及计算次数(用HashMap)
package ch007;
import java.util.*;
public class Chardemo {
public static void main(String[] args) {
String str = "today is a special day";
HashMap<Character,Integer> ccMap = new HashMap<Character,Integer>();
char[] ac = str.toCharArray();
for(char c : ac) {
if(ccMap.get(c)==null)
ccMap.put(c, 1);
else {
int i=ccMap.get(c);
ccMap.put(c,i+1);
}
}
Set<Character> cs = ccMap.keySet();
for(char c : cs) {
System.out.println("'"+c+"'"+" : "+ccMap.get(c));
}
}
}
流和文件
文件
File类
package ch007;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
public class FileDemo {
public static void main(String[] args) {
System.out.println("请输入一个文件名:");
Scanner s = new Scanner(System.in);
String pathName = s.next();
File file = new File(pathName);
if(!file.exists()) {
try {
file.createNewFile();
}catch(IOException e) {
e.printStackTrace();
}
}
System.out.println("文件是否存在:"+file.exists());
System.out.println("是文件吗:"+file.isFile());
System.out.println("是目录吗:"+file.isDirectory());
System.out.println("名称:"+file.getName());
System.out.println("路径:"+file.getPath());
System.out.println("绝对路径:"+file.getAbsolutePath());
//时间的几种表现形式
System.out.println("最后修改时间:"+file.lastModified());
System.out.println("最后修改时间1:"+new Date(file.lastModified()).toString());
System.out.println("文件大小:"+file.length());
}
}
文件列表器
package ch007;
import java.io.File;
public class ListDemo {
public static void main(String[] args) {
File file = new File("D:\\JAVA项目\\First");
if(file.isDirectory()) {
String[] fileNames = file.list();
for(String fileName : fileNames) {
System.out.println(fileName);
}
}
}
}
package ch008;
import java.io.File;
public class ListFileDemo {
public static void main(String[] args) {
File file = new File("D:\\JAVA项目\\First");
if(file.isDirectory()) {
File[] files = file.listFiles();
for(File f : files) {
if(f.isFile()) {
System.out.println("文件: "+f);
}else {
System.out.println("目录: "+f);
}
}
}
}
}
FileNameFilter是一接口,它只有一个accept()方法,所以只需要定义一个类来实现这个接口,或者可以定义一个匿名类。
package ch008;
import java.io.File;
import java.io.FilenameFilter;
public class HtmlList {
public static void main(String[] args) {
File file = new File("D:\\JAVA项目\\First");
if(file.exists()&&file.isDirectory()) {
//创建FileNameFilter类型的匿名类,并作为参数传入到List方法中
String[]fileNames = file.list(new FilenameFilter() {
public boolean accept(File dir,String name) {
return(name.endsWith(".html")|| name.endsWith(".txt"));
}
});
for(String fileName : fileNames) {
System.out.println(fileName);
}
}
}
}
流
字节流 InputStream/OutStream
package ch008;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
FileInputStream fi = null;
try {
//利用路径创建一个FileInputStream类型的变量
fi = new FileInputStream("d:\\test.txt");
//从流对象中读取内容
int value = fi.read();
System.out.println("文件中的内容是:"+(char)value);
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(fi!=null) {
fi.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
package ch008;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fo = null;
try {
//利用路径创建一个FileOutputStream类型的变量
fo = new FileOutputStream("d:\\test.txt");
for(int i=0;i<26;i++) {
fo.write(65+i);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(fo!=null) {
fo.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
过滤流
package ch008;
import java.io.*;
public class BufferedInputStreamDemo {
public static void main(String[] args) {
BufferedInputStream bo = null;
try {
bo = new BufferedInputStream(
new FileInputStream("d:\\test.txt"));
int result = 0;
System.out.println("文件中的结果:");
while((result=bo.read())!=-1) {
System.out.print((char)result);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(bo!=null) {
bo.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
package ch008;
import java.io.*;
public class BufferedOutputStreamDemo {
public static void main(String[] args) {
BufferedOutputStream bo = null;
try {
bo = new BufferedOutputStream(
new FileOutputStream("d:\\test.txt"));
for(int i=0;i<26;i++) {
bo.write(65+i);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(bo!=null) {
bo.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
字符流处理的是字符,Java采用Unicode字符编码,对每一个字符,jvm会为其分配两个字节的内存,代码同字节流相似。
对象流
package ch008;
import java.io.*;
public class ObjectOutputStreamDemo {
public static void main(String[] args) {
ObjectOutputStream obs = null;
try {
//利用路径创建一个ObjectOutputStream类型的变量
obs = new ObjectOutputStream(
new FileOutputStream("d:\\test.txt"));
Person person = new Person("20170300536","张三",20);
obs.writeObject(person);
obs.flush();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(obs!=null) {
obs.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
//定义一个person实体类
class Person implements Serializable{
private String Id;
private String name;
private int age;
public Person(String Id,String name,int age) {
this.Id=Id;
this.name=name;
this.age=age;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
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;
}
}
package ch008;
import java.io.*;
public class ObjectInputStreamDemo {
public static void main(String[] args) {
ObjectInputStream ojs = null;
try {
ojs = new ObjectInputStream(
new FileInputStream("d:\\test.txt"));
Object obj = ojs.readObject();
if(obj!=null) {
Person person = (Person)obj;
System.out.println("编号为:"+person.getId()+"姓名为:"+person.getName()+"年龄:"+person.getAge());
}
}catch(Exception ex) {
ex.printStackTrace();
}finally {
try {
if(ojs!=null) {
ojs.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}