JAVA从入门到精通习题

1.编写一个程序,定义局部变量sum,并求出1+2+3+…+99+100之和,赋值给sum,并输出sum的值。

public class Test {

public static void main(String args[]){

int sum=0;

for(int i=1;i<=100;i++){

sum=sum+i;

}

System.out.println("1+2+3+...+100="+sum);

}

}

2.编写程序,要求运行后要输出long类型数据的最小数和最大数。

public class Test {

public static void main(String args[]){

Long m=Long.MAX_VALUE;

Long n=Long.MIN_VALUE;

System.out.println("long类型的最大数是:"+m+",最小数是:"+n);

}

}

3.编写程序,计算表达式“((123456799)>(976543213))? true : false”的值。

public class Test {

public static void main(String args[]){

Boolean result=((12345679*9)>(97654321*3))?true:false;

System.out.println(result);

}

}

4.编写程序,实现生成一随机字母(a-z,A-Z),并输出,运行结果如下图所示。

拓展知识。

⑴ Math.random()返回随机 double 值,该值大于等于 0.0 且小于 1.0。

例如: double rand = Math.random(); // rand 储存着[0,1) 之间的一个小数

⑵ 大写字母A~Z对应整数65 ~ 90、小写字母a~z对应整数97 ~ 122。

public class Test {

public static void main(String args[]){

int a=(int)(Math.random()*(122-65)+65);

if(a>=65&&a<=90||a>=97&&a<=122){

System.out.println((char)a);

}else{

System.out.println("无字母输出");

}

}

}

5.编写程序,实现产生(或输入)一随机字母(a-z,A-Z),转为大写形式,并输出。

public class Test {

public static void main(String args[]){

int a=(int)(Math.random()*(122-65)+65);

if(a>=65&&a<=90){

System.out.println("转换前:"+(char)a);

System.out.println("转换后:"+(char)a);

}else if(a>=97&&a<=122){

System.out.println("转换前:"+(char)a);

System.out.println("转换后:"+(char)(a-32));

}else{

System.out.println("无字母输出");

}

}

}

6.编写程序,使用程序产生1-12之间的某个整数(包括1和12),然后输出相应月份的天数(2月按28天算)。运行结果如下图所。

public class Test {

public static void main(String args[]){

int month=(int)(Math.random()*12+1);

switch (month){

case 1:

System.out.println("1月共有31天");

break;

case 2:

System.out.println("2月共有28天");

break;

case 3:

System.out.println("3月共有31天");

break;

case 4:

System.out.println("4月共有30天");

break;

case 5:

System.out.println("5月共有31天");

break;

case 6:

System.out.println("6月共有30天");

break;

case 7:

System.out.println("7月共有31天");

break;

case 8:

System.out.println("8月共有31天");

break;

case 9:

System.out.println("9月共有30天");

break;

case 10:

System.out.println("10月共有31天");

break;

case 11:

System.out.println("11月共有30天");

break;

case 12:

System.out.println("12月共有31天");

break;

default:

System.out.println("输出错误");

break;

}

}

}

7.编写程序,判断某一年是否是闰年。

import java.util.Scanner;

public class Test {

public static void main(String args[]){

System.out.println("请输入年份:");

Scanner scanner=new Scanner(System.in);

int year=scanner.nextInt();

if(year<0||year>3000){

System.out.println("输入错误");

}

if(year%4==0&&year%100!=0){

System.out.println(year+"年是闰年");

}else if(year%400==0){

System.out.println(year+"年是闰年");

}else{

System.out.println(year+"年不是闰年");

}

}

}

8.编写程序,对int[] a = {25, 24, 12, 76, 98, 101, 90, 28}数组进行排序。排序算法有很多种,读者可先编写程序实现冒泡法排序,运行结果如下图所示。(注:冒泡排序也可能有多种实现版本,本题没有统一的答案。)

public class Test {

public static void main(String args[]){

int[] a={25,24,12,76,98,101,90,28};

System.out.println("排序前数组a元素为:");

for(int i=0;i

System.out.print("a["+i+"]="+a[i]+" ");

}

System.out.println(" ");

for(int j=0;j

for(int k=0;k

if(a[k]>a[k+1]){

int temp=a[k];

a[k]=a[k+1];

a[k+1]=temp;

}

}

}

System.out.println("排序后数组a元素为:");

for(int m=0;m

System.out.print("a["+m+"]="+a[m]+" ");

}

}

}

9.定义一个包含name、age和like属性的Person类,实例化并给对象赋值,然后输出对象属性。

class Person{

String name;

int age;

String like;

public Person(String name,int age,String like){

this.name=name;

this.age=age;

this.like=like;

}

public void print(){

System.out.println("姓名:"+name+",年龄:"+age+",喜欢:"+like);

}

}

public class Test {

public static void main(String args[]){

Person p[]=new Person[3];

p[0]=new Person("张三",20,"猫");

p[1]=new Person("李四",56,"狗");

p[2]=new Person("王五",12,"猪");

for(int i=0;i

p[i].print();

}

}

}

10.定义一个book类,包括属性title(书名)和price(价格),并在该类中定义一个方法printInfo(),来输出这2个属性。然后再定义一个主类,其内包括主方法,在主方法中,定义2个book类的实例bookA和bookB,并分别初始化title和price的值。然后将bookA赋值给bookB,分别调用printInfo(),查看输出结果并分析原因。

class Book{

String title;

int price;

public Book(String title,int price){

this.title=title;

this.price=price;

}

public void printInfo(){

System.out.println("书名:"+title+",价格:"+price);

}

}

public class Test {

public static void main(String args[]){

Book bookA=new Book("老人与海",56);

Book bookB=new Book("百万富翁",70);

bookB=bookA;

bookA.printInfo();

bookB.printInfo();

}

}

11.定义一个book类,包括属性title(书名)、price(价格)及pub(出版社),pub的默认值是“天天精彩出版社”,并在该类中定义方法getInfo(),来获取这三个属性。再定义一个公共类BookPress,其内包括主方法。在主方法中,定义3个book类的实例b1,b2和b3,分别调用各个对象的getInfo()方法,如果“天天精彩出版社”改名为“每日精彩出版社”,请在程序中实现实例b1,b2和b3的pub改名操作。

class Book{

String title;

int price;

String pub;

public Book(String title,int price){

this.title=title;

this.price=price;

this.pub="天天精彩出版社";

}

public void getInfo(){

System.out.println("书名:"+title+",价格:"+price+",出版社:"+pub);

}

public void setPub(String pub){

this.pub=pub;

}

}

public class Test {

public static void main(String args[]){

Book b1=new Book("老人与海",56);

Book b2=new Book("百万富翁",70);

Book b3=new Book("海蒂",42);

b1.setPub("每日精彩出版社");

b1.getInfo();

b2.getInfo();

b3.getInfo();

}

}

12.编程实现,现在有如下的一个数组。

int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}

要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为。

int newArr[]={1,3,4,5,6,6,5,4,7,6,7,5}

提示

需要确定新数组的大小,需要知道原始数组之中不为0的个数,可编写一个方法完成;根据统计的结果开辟一个新的数组;将原始数组之中不为0的数据拷贝到新数组之中。)

public class Test {

public static void main(String args[]){

int[] oldArr={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};

for(int j:oldArr){

System.out.print(j+" ");

}

System.out.println(" ");

int count=0;

for(int i=0;i

if(oldArr[i]==0){

count=count+1;

}

}

System.out.println("0的个数:"+count);

int[] newArr=new int[oldArr.length-count];

int m=0;

for(int k=0;k

if(oldArr[k]!=0){

newArr[m]=oldArr[k];

m++;

}

}

for(int n:newArr){

System.out.print(n+" ");

}

}

}

13.编程实现,要求程序输出某两个整数之间的随机数。

import java.util.Scanner;

public class Test {

public static void main(String args[]){

System.out.println("请输入两个整数:");

Scanner scanner=new Scanner(System.in);

int i=scanner.nextInt();

int j=scanner.nextInt();

scanner.close();

double result=Math.random()*(j-i)+i;

System.out.println(i+"和"+j+"间的随机数为:"+result);

}

}

14.定义枚举类型WeekDay,使用枚举类型配合switch语法,完善下面的代码,尝试完善完成如下功能:wd=Mon时,输出"Do Monday work",wd=Tue时,输出"DoTuesday work",…,依此类推,当wd不为枚举元素值时输出"I don't know whichis day"。

enum WeekDay{Sun,Mon,Tue,Wed,Thu,Fri,Sat};

public class Test {

public static void main(String args[]){

WeekDay wd=WeekDay.Mon;

switch(wd){

case Mon:

System.out.println("Do Monday Work");

break;

case Tue:

System.out.println("Do Tuesday Work");

break;

case Wed:

System.out.println("Do Wednesday Work");

break;

case Thu:

System.out.println("Do Thursday Work");

break;

case Fri:

System.out.println("Do Friday Work");

break;

case Sat:

System.out.println("Do Saturday Work");

break;

case Sun:

System.out.println("Do Sunday Work");

break;

default:

System.out.println("I don`t know which is day");

break;

}

}

}

15.建立一个人类(Person)和学生类(Student),功能要求如下。

⑴ Person中包含4个数据成员name、addr、sex和age,分别表示姓名、地址、类别和年龄。设计一个输出方法talk()来显示这4种属性。

⑵ Student类继承Person类,并增加成员Math、English存放数学与英语成绩。用一个6参构造方法、一个两参构造方法、一个无参构造方法和覆写输出方法talk()用于显示6种属性。对于构造方法参数个数不足以初始化4个数据成员时,在构造方法中采用自己指定默认值来实施初始化。

class Person{

private String name;

private String addr;

private char sex;

private int age;

public Person(){

}

public Person(String name,char sex){

this.name=name;

this.sex=sex;

}

public Person(String name,String addr,char sex,int age){

this.name=name;

this.addr=addr;

this.sex=sex;

this.age=age;

}

public String talk(){

return "姓名:"+this.getName()+",地址:"

+this.getAddr()+",性别:"+this.getSex()+",年龄:"

+this.getAge();

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAddr() {

return addr;

}

public void setAddr(String addr) {

this.addr = addr;

}

public char getSex() {

return sex;

}

public void setSex(char sex) {

this.sex = sex;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}

class Student extends Person{

float Math;

float English;

public Student(){

}

public Student(String name,char sex){

super(name,sex);

}

public Student(String name,String addr,char sex,int age,float Math,float English){

super(name,addr,sex,age);

this.Math=Math;

this.English=English;

}

public float getMath() {

return Math;

}

public void setMath(float math) {

Math = math;

}

public float getEnglish() {

return English;

}

public void setEnglish(float english) {

English = english;

}

public String talk(){

return "姓名:"+this.getName()+",地址:"

+this.getAddr()+",性别:"+this.getSex()+",年龄:"

+this.getAge()+",数学成绩:"+this.getMath()+",英语成绩:"

+this.getEnglish();

}

}

public class Test{

public static void main(String[] args){

Student student1=new Student();

System.out.println(student1.talk());

Student student2=new Student("张三",'男');

System.out.println(student2.talk());

Student student3=new Student("李四","长沙",'女',20,90.5f,89.5f);

System.out.println(student3.talk());

}

}

16.定义一个Instrument(乐器)类,并定义其公有方法play(),再分别定义其子类Wind(管乐器), Percussion(打击乐器),Stringed(弦乐器),覆写play方法,实现每种乐器独有play方式。最后在测试类中使用多态的方法执行每个子类的play()方法。

class Instrument{

public String play(){

return "演奏";

}

}

class Wind extends Instrument{

public String play(){

return "管乐器演奏";

}

}

class Percussion extends Instrument{

public String play(){

return "打击乐器演奏";

}

}

class Stringed extends Instrument{

public String play(){

return "弦乐器演奏";

}

}

public class Test{

public static void main(String[] args){

Wind wind=new Wind();

System.out.println(wind.play());

Percussion percussion=new Percussion();

System.out.println(percussion.play());

Stringed stringed=new Stringed();

System.out.println(stringed.play());

}

}

17.设计一个限制子类的访问的抽象类实例,要求在控制台输出如下结果。

教师→姓名:刘三,年龄:50,职业:教师

工人→姓名:赵四,年龄:30,职业:工人

abstract class Person

{

private String name;

private int age;

public Person(String name,int age){

this.name=name;

this.age=age;

}

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;

}

}

class Teacher extends Person{

private String job;

public Teacher(String name,int age,String job){

super(name,age);

this.job=job;

}

public String getJob() {

return job;

}

public void setJob(String job) {

this.job = job;

}

public String print(){

return "教师->姓名:"+getName()+",年龄:"+getAge()+",职业:"+getJob();

}

}

class Worker extends Person{

private String job;

public Worker(String name,int age,String job){

super(name,age);

this.job=job;

}

public String getJob() {

return job;

}

public void setJob(String job) {

this.job = job;

}

public String print(){

return "工人->姓名:"+getName()+",年龄;"+getAge()+",职业:"+getJob();

}

}

public class Test{

public static void main(String[] args){

Teacher teacher=new Teacher("刘三",50,"教师");

System.out.println(teacher.print());

Worker worker=new Worker("赵四",30,"工人");

System.out.println(worker.print());

}

}

18.利用接口及抽象类设计实现

⑴ 定义接口圆形CircleShape(),其中定义常量PI,默认方法area计算圆面积;

⑵ 定义圆形类Circle实现接口CircleShape,包含构造方法和求圆周长方法;

⑶ 定义圆柱继承Circle实现接口CircleShape,包含构造方法,圆柱表面积,体积;

⑷ 从控制台输入圆半径,输出圆面积及周长;

⑸ 从控制台输入圆柱底面半径及高,输出圆柱底面积、圆柱表面积及体积。

import java.util.Scanner;

interface CircleShape{

public static final double PI=3.14;

default public double area(double r){

return PI*r*r;

}

}

class Circle implements CircleShape{

private double r;

public Circle(double r){

this.r=r;

}

public double circle(double r){

return 2*PI*r;

}

}

class Cylinder extends Circle implements CircleShape{

private double h;

public Cylinder(double r,double h){

super(r);

this.h=h;

}

public double SurfaceArea(double r,double h){

double bottomArea=area(r);

double lateralArea=circle(r)*h;

return 2*bottomArea+lateralArea;

}

public double Volume(double r,double h){

return area(r)*h;

}

}

public class Test{

public static void main(String[] args){

double r=0;

double h=0;

System.out.println("请输入圆的半径:");

Scanner scanner=new Scanner(System.in);

r=scanner.nextDouble();

Circle circle=new Circle(r);

System.out.println("圆的半径为:"+r+",圆的面积为:"+circle.area(r)

+",周长为:"+circle.circle(r));

System.out.println("请输入圆柱的半径和高:");

Scanner scanner1=new Scanner(System.in);

r=scanner1.nextDouble();

h=scanner1.nextDouble();

scanner1.close();

Cylinder cylinder=new Cylinder(r,h);

System.out.println("圆柱的半径和高为:"+r+","+h+",圆柱底面积为:"

+cylinder.area(r)+",圆柱表面积为:"+cylinder.SurfaceArea(r,h)

+",圆柱的体积为:"+cylinder.Volume(r,h));

}

}

19.定义一个包含“name”、“age”和“sex”的对象,使用匿名对象输出对象实例。

class Person{

String name;

int age;

char sex;

public Person(String name,int age,char sex){

this.name=name;

this.age=age;

this.sex=sex;

}

public String print(){

return "姓名:"+name+",年龄:"+age+",性别:"+sex;

}

}

public class Test{

public static void main(String[] args){

System.out.println(new Person("张三",25,'男').print());

}

}

20.完成一个统计Book类产生实例化对象的个数。

class Book{

static int num=0;

public Book(){

num++;

System.out.println("实例化对象");

}

}

public class Test{

public static void main(String[] args){

new Book();

new Book();

new Book();

new Book();

new Book();

System.out.println(Book.num);

}

}

21.分别以如下形式输出当前的时间:形式一:2014-08-08;形式二:2014-08-08 18-40 123;形式三:2014年08月08日;形式四:2014年08月08日 16时40分123毫秒。

import java.time.LocalDateTime;

import java.time.format.*;

public class Test{

public static void main(String[] args){

LocalDateTime localDateTime1=LocalDateTime.now();

DateTimeFormatter f1=DateTimeFormatter.ofPattern("uuuu-MM-dd");

DateTimeFormatter f2=DateTimeFormatter.ofPattern("uuuu-MM-dd HH-mm SSS");

DateTimeFormatter f3=DateTimeFormatter.ofPattern("uuuu年MM月dd日");

DateTimeFormatter f4=DateTimeFormatter.ofPattern("uuuu年MM月dd日 HH时mm分 SSS毫秒");

String str1=localDateTime1.format(f1);

String str2=localDateTime1.format(f2);

String str3=localDateTime1.format(f3);

String str4=localDateTime1.format(f4);

System.out.println("格式一:"+str1);

System.out.println("格式二:"+str2);

System.out.println("格式三:"+str3);

System.out.println("格式四:"+str4);

}

}

22.编写一个Java程序,完成以下功能。

⑴ 声明一个名为name的String对象,内容是“My name is Networkcrazy”;

⑵ 输出字符串的长度;

⑶ 输出字符串的第一个字符;

⑷ 输出字符串的最后一个字符;

⑸ 输出字符串的第一个单词;

⑹ 输出字符串crazy的位置(从0开始编号的位置)。

public class Test{

public static void main(String[] args){

String str="My name is Networkcrazy";

System.out.println("长度:"+str.length());

System.out.println("第一个字符:"+str.charAt(0));

System.out.println("最后一个字符:"+str.charAt(str.length()-1));

String data[]=str.split(" ");

System.out.println("第一个单词为:"+data[0]);

System.out.println("字符串crazy的位置为:"+str.indexOf("crazy"));

}

}

23.定义一个Message类在主方法之中定义一个对象msg以及一个方法fun();temp为临时变量。

(1)

class Messagge{

private double salary;

public Messagge(double salary){

this.salary=salary;

}

public double getSalary() {

return salary;

}

public void setSalary(double salary) {

this.salary = salary;

}

}

public class Test{

public static void main(String[] args){

Messagge msg=new Messagge(800.0);

fun(msg);

System.out.println(msg.getSalary());

}

public static void fun(Messagge msg){

Messagge temp=msg;

temp.setSalary(2000.0);

}

}

(2)

public class Test{

public static void main(String[] args){

String str="Hello";

fun(str);

System.out.println(str);

}

public static void fun(String str){

String temp=str;

temp="world";

}

}

(3)

class Message{

private String info;

public Message(String info){

this.info=info;

}

public String getInfo() {

return info;

}

public void setInfo(String info) {

this.info = info;

}

}

public class Test{

public static void main(String[] args){

Message msg=new Message("Hello");

fun(msg);

System.out.println(msg.getInfo());

}

public static void fun(Message msg){

Message temp=msg;

temp.setInfo("world");

}

}

24.编写一段程序,声明一个包,在另一个包中使用import语句访问使用,要求:

⑴ 声明一个包point,其中定义Point类,包含x,y坐标,构造方法,获取x,y坐标及设置;

⑵ 声明另一个包,导入包point,其中在新包中定义Circle类,半径,构造方法,获取、设置半径。

设计程序实现圆的实例化,并输出半径和圆心。

package point;

public class Point {

private double X;

private double Y;

private Point(double X,double Y){

this.X=X;

this.Y=Y;

}

public static Point getInstance(double X,double Y){

return new Point(X,Y);

}

public double getX() {

return X;

}

public void setX(double x) {

X = x;

}

public double getY() {

return Y;

}

public void setY(double y) {

Y = y;

}

public String toString(){

return "(" + X + "," + Y + ")";

}

}

package Test;

import point.*;

public class Circle {

private double r;

private Point point;

public Circle(double r,double X,double Y){

point=Point.getInstance(X,Y);

this.r=r;

}

public double getR() {

return r;

}

public void setR(double r) {

this.r = r;

}

public void print() {

System.out.println("半径为" + this.r + ",圆心为" + point);

}

}

package Test;

import Test.Circle;

public class Test {

public static void main(String[] args){

Circle circle=new Circle(2,5,3);

circle.print();

}

}

25.编写应用程序,从命令行输入两个整数参数,求它们的商。要求程序中捕获可能发生的异常。

package Test;

import java.util.InputMismatchException;

import java.util.Scanner;

public class Test {

public static void main(String[] args){

try {

Scanner scanner = new Scanner(System.in);

int i = scanner.nextInt();

int j = scanner.nextInt();

scanner.close();

int result = i / j;

System.out.println("商为:"+result);

}catch(InputMismatchException ex){

System.out.println("输入格式错误:"+ex);

}catch(ArithmeticException e){

System.out.println("算术错误:"+e);

}

}

}

26.编写一段程序,使用ArrayList类存储以下元素:“one”、“two”、“three”、“four”,并通过Iterator迭代输出ArrayList中的内容。

package Test;

import java.util.ArrayList;

import java.util.Iterator;

public class Test {

public static void main(String[] args){

ArrayList arrayList=new ArrayList();

arrayList.add("one");

arrayList.add("two");

arrayList.add("three");

arrayList.add("four");

Iterator iterator=arrayList.iterator();

while(iterator.hasNext()){

System.out.println(iterator.next());

}

}

}

27.定义Student类,该类不实现Comparable接口,定义一个Comparator类比较两个Student对象所在班级名称和名字,班级名相同时用名字进行排序,使用TreeSet观察排序的结果。

package Test;

import java.util.Comparator;

import java.util.Iterator;

import java.util.TreeSet;

class Student{

String className;

String name;

public Student(String className,String name){

this.className=className;

this.name=name;

}

@Override

public String toString(){

return "姓名:"+name+",班级名字:"+className+"\n";

}

public String getClassName() {

return className;

}

public void setClassName(String className) {

this.className = className;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

class StudentComparator implements Comparator{

@Override

public int compare(Student s1,Student s2){

String studentClassName1=s1.getClassName();

String studentClassName2=s2.getClassName();

String studentName1=s1.getName();

String studentName2=s2.getName();

if(studentClassName1.compareTo(studentClassName2)!=0){

return studentClassName1.compareTo(studentClassName2);

}else{

return studentName1.compareTo(studentName2);

}

}

}

public class Test {

public static void main(String[] args){

TreeSet treeSet=new TreeSet(new StudentComparator());

treeSet.add(new Student("3班","赵六"));

treeSet.add(new Student("1班","张三"));

treeSet.add(new Student("2班","王五"));

treeSet.add(new Student("1班","李四"));

Iterator iterator=treeSet.iterator();

while(iterator.hasNext()){

Student s=iterator.next();

System.out.println(s.toString());

}

}

}

28.定义一个Student类(包含班级和姓名属性),然后定义多个StudentItem对象,并以姓名为键,对象为值添加到HashMap中,分别实现对该集合的查看、修改和删除。

package Test;

import java.util.*;

class Student{

String className;

String name;

public Student(String className,String name){

this.className=className;

this.name=name;

}

@Override

public String toString(){

return "姓名:"+name+",班级名字:"+className;

}

public String getClassName() {

return className;

}

public void setClassName(String className) {

this.className = className;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

public class Test {

public static void main(String[] args){

Student s1=new Student("1班","张三");

Student s2=new Student("2班","李四");

Student s3=new Student("3班","王五");

Student s4=new Student("4班","赵六");

HashMaphashMap=new HashMap();

hashMap.put("张三",s1);

hashMap.put("李四",s2);

hashMap.put("王五",s3);

hashMap.put("赵六",s4);

Set> set=hashMap.entrySet();

Iterator>iterator=set.iterator();

while(iterator.hasNext()){

Map.Entry mapEntry=(Map.Entry)iterator.next();

System.out.print(mapEntry.getKey()+"->");

System.out.println(mapEntry.getValue());

}

System.out.println();

Student s=hashMap.get("张三");

s.setClassName("10班");

hashMap.put("张三",s);

System.out.println("修改后:"+hashMap.get("张三"));

System.out.println();

hashMap.remove("李四");

Set> set1=hashMap.entrySet();

Iterator>iterator1=set1.iterator();

while(iterator1.hasNext()){

Map.Entry mapEntry1=(Map.Entry)iterator1.next();

System.out.print(mapEntry1.getKey()+"->");

System.out.println(mapEntry1.getValue());

}

}

}

29.定义一个可以用来接收用户登录信息的Annotation。其中用户名和密码要求通过Annotation设置到验证的方法中,如下所示。

@LoginInfo(name="用户名",password = "密码")

public boolean login(String name,String password){

}

之后编写程序用键盘输入用户的登录信息,并通过login()方法判断输入的用户名和密码是否正确。

package Test;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Target(value = {ElementType.METHOD})

@Retention(value = RetentionPolicy.RUNTIME)

public @interface LoginInfo{

public String name();

public String password();

}

package Test;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.lang.reflect.Method;

class Reflect {

private String name;

private String password;

BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));

public String getName() throws IOException{

System.out.println("请输入用户名:");

name=bufferedReader.readLine();

return name;

}

public String getPassword() throws IOException{

System.out.println("请输入密码:");

password=bufferedReader.readLine();

return password;

}

@LoginInfo(name="张三",password = "123456")

public boolean login(String name,String password){

boolean flag=false;

Method m=null;

try{

m=Reflect.class.getMethod("login", String.class, String.class);

}catch (Exception e){

e.printStackTrace();

}

LoginInfo loginInfo=m.getAnnotation(LoginInfo.class);

if(loginInfo.name().equals(name)&&loginInfo.password().equals(password)){

flag=true;

}

return flag;

}

}

package Test;

import java.io.IOException;

public class Test {

public static void main(String[] args) throws IOException {

String name;

String password;

Reflect reflect=new Reflect();

name=reflect.getName();

password=reflect.getPassword();

if(reflect.login(name,password)==true){

System.out.println("用户名密码正确");

}else{

System.out.println("用户名密码错误");

}

}

}

30.编写一个多线程处理的程序,其他线程运行10秒后,使用main方法中断其他线程。

package Test;

class MyThread implements Runnable{

public void run(){

try{

System.out.println("线程休眠10s");

Thread.sleep(10000);

System.out.println("休眠结束");

}catch (InterruptedException e){

System.out.println("线程被中断");

}

System.out.println("线程继续运行");

}

}

public class Test {

public static void main(String[] args){

MyThread myThread=new MyThread();

Thread thread=new Thread(myThread);

thread.start();

try{

Thread.sleep(1000);

}catch (InterruptedException e){

e.printStackTrace();

}

System.out.println("main方法结束其他线程");

System.out.println("main方法退出");

}

}

31.设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果新的电脑没有生产出来,则搬运工就要等待;如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产。在main方法中结束其他线程,然后输出生产的电脑数量。

package Test;

class Computer{

private String name;

private static int sum=1;

private boolean flag=true;

public Computer(String name){

this.name=name;

}

public synchronized void set(){

if(!flag){

try{

super.wait();

}catch(InterruptedException e){

e.printStackTrace();

}

}

try{

Thread.sleep(1000);

}catch (InterruptedException e){

e.printStackTrace();

}

System.out.println("生产了"+this.name+",现在已经生产了"+sum+"台电脑");

sum++;

flag=false;

super.notify();

}

public synchronized void get(){

if(flag){

try{

super.wait();

}catch (InterruptedException e){

e.printStackTrace();

}

}

try{

Thread.sleep(1000);

}catch (InterruptedException e){

e.printStackTrace();

}

System.out.println("搬走了"+this.name+"");

flag=true;

super.notify();

}

}

class ComThread implements Runnable{

public void run(){

for(int i=0;i<10;i++){

Computer computer=new Computer("电脑"+i);

computer.set();

computer.get();

}

}

}

public class Test {

public static void main(String[] args){

ComThread comThread=new ComThread();

Thread thread=new Thread(comThread);

thread.start();

}

}

32.递归列出指定目录下的所有扩展名为txt的文件。

(1)

package Test;

import java.io.File;

public class TestTxt {

public static void main(String[] args){

File file=new File("D:"+File.separator+"TestTxt");

OutputAllTxtFiles(file);

}

public static void OutputAllTxtFiles(File file){

File[] files=file.listFiles();

if(files!=null){

for(File f:files){

if(f.isDirectory()){

OutputAllTxtFiles(f);

}else{

if(f.getName().endsWith(".txt")){

System.out.println(f);

}

}

}

}

}

}

(2)

package Test;

import java.io.File;

import java.io.IOException;

import java.nio.file.FileVisitOption;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.stream.Stream;

public class Test {

public static void main(String[] args)throws IOException {

File file=new File("D:"+File.separator+"TestTxt");

Path path=file.toPath();

Streamfiledata= Files.walk(path,Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS);

filedata.forEach((p)->System.out.println(p.getFileName()));

filedata.close();

}

}

33.利用byte[]、BufferedInputStream 和 BufferedOutputStream 完成单个文件的复制。可复制图片、文本文件,复制后打开文件,对比两个文件是否内容一致,从而判断程序的正确性。(提示 先从一个文件中读取,再写进另一个文件)。

package Test;

import java.io.*;

public class Test {

public static void main(String[] args){

BufferedInputStream bufferedInputStream=null;

BufferedOutputStream bufferedOutputStream=null;

try{

File file=new File("D:"+File.separator+"1.txt");

File file1=new File("D:"+File.separator+"2.txt");

FileInputStream fileInputStream=new FileInputStream(file);

FileOutputStream fileOutputStream=new FileOutputStream(file1);

bufferedInputStream=new BufferedInputStream(fileInputStream);

bufferedOutputStream=new BufferedOutputStream(fileOutputStream);

byte b1[]=new byte[1024];

int i=0;

while((i=bufferedInputStream.read(b1)) != -1){

bufferedOutputStream.write(b1,0,i);

}

}catch (FileNotFoundException e){

e.printStackTrace();

}catch (IOException e){

e.printStackTrace();

}finally {

if(bufferedInputStream!=null){

try{

bufferedInputStream.close();

}catch (IOException e){

e.printStackTrace();

}

}

if(bufferedOutputStream!=null){

try{

bufferedOutputStream.close();

}catch (IOException e){

e.printStackTrace();

}

}

}

}

}

34.有一个Student类,有学号(id)、姓名(name)、各科成绩(math、os、java)。从控制台输入信息创建两个学生对象,并将该类序列化到文件。注意要进行简单的输入验证。

package Test;

import java.io.*;

import java.util.Scanner;

@SuppressWarnings("serial")

class Student implements Serializable{

int id;

String name;

Double math,os,java;

public Student(int id,String name,Double math,Double os,Double java){

if(id>0&&name.length()>0&&math<=100&&

math>=0&&os<=100&&os>=0&&java<=100&java>=0) {

this.id = id;

this.name = name;

this.math = math;

this.os = os;

this.java = java;

}else{

System.out.println("输入错误!");

}

}

@Override

public String toString(){

return "学号:"+id+",姓名:"+name+",数学:"+math+",操作系统:"+os+",java:"+java;

}

}

public class Test {

public static void serialize(File file,Student student)throws Exception{

OutputStream outputStream=new FileOutputStream(file);

ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);

objectOutputStream.writeObject(student);

objectOutputStream.close();

}

public static void deserialize(File file)throws Exception{

InputStream inputStream=new FileInputStream(file);

ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);

Student student=(Student)objectInputStream.readObject();

System.out.println(student);

}

public static void main(String[] args){

int i=0,j=0;

String name1,name2;

Double math1,math2,os1,os2,java1,java2;

Scanner scanner=new Scanner(System.in);

while(true) {

System.out.println("请输入学生信息,输入数字0结束输入");

int exit=scanner.nextInt();

if(exit==0){

scanner.close();

break;

}

System.out.println("请输入学生一学号:");

i = scanner.nextInt();

System.out.println("请输入学生一姓名:");

name1 = scanner.next();

System.out.println("请输入学生一数学成绩:");

math1 = scanner.nextDouble();

System.out.println("请输入学生一操作系统成绩:");

os1 = scanner.nextDouble();

System.out.println("请输入学生一java成绩:");

java1 = scanner.nextDouble();

Student student1 = new Student(i, name1, math1, os1, java1);

System.out.println("请输入学生二学号:");

j=scanner.nextInt();

System.out.println("请输入学生二姓名:");

name2=scanner.next();

System.out.println("请输入学生二数学成绩:");

math2=scanner.nextDouble();

System.out.println("请输入学生二操作系统成绩:");

os2=scanner.nextDouble();

System.out.println("请输入学生二java成绩:");

java2=scanner.nextDouble();

Student student2=new Student(j,name2,math2,os2,java2);

try {

File file = new File("D:" + File.separator + "student.txt");

System.out.println("输入完成,打印:");

serialize(file, student1);

deserialize(file);

serialize(file, student2);

deserialize(file);

}catch (Exception e){

e.printStackTrace();

}

}

}

}

35.编写一个服务器端/客户端程序,对客户端输入的字符串,服务器端以“客户端:”开头再返回。

服务端:

package Test;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.net.ServerSocket;

import java.net.Socket;

public class EchoServer {

public static void main(String[] args) throws Exception{

ServerSocket serverSocket=new ServerSocket(8888);

Socket client=null;

boolean flag=true;

while (flag){

System.out.println("等待客户端连接:");

client=serverSocket.accept();

BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(client.getInputStream()));

PrintStream printStream=new PrintStream(client.getOutputStream());

boolean temp=true;

while (temp) {

String str=bufferedReader.readLine();

if(str==null||"".equals(str)){

temp=false;

break;

}

if("bye".equals(str)){

temp=false;

break;

}

printStream.println("客户端:"+str);

}

printStream.close();

client.close();

}

serverSocket.close();

}

}

客户端:

package Test;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintStream;

import java.net.Socket;

public class EchoClient {

public static void main(String[] args) throws Exception{

Socket client=new Socket("localhost",8888);

BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));

BufferedReader buff=null;

buff=new BufferedReader(new InputStreamReader(client.getInputStream()));

PrintStream printStream=new PrintStream(client.getOutputStream());

boolean flag=true;

while (flag){

System.out.println("请输入要发送的内容:");

String str=bufferedReader.readLine();

if(str==null||"".equals(str)){

flag=false;

break;

}

if("bye".equals(str)){

flag=false;

break;

}

printStream.println(str);

System.out.println(buff.readLine());

}

client.close();

}

}

作者:一只小橘猫

链接:https://www.jianshu.com/p/d651c23bda6c

來源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

java从入门到精通 答案_JAVA从入门到精通习题相关推荐

  1. java期末考试2013及答案_java笔试经典(题及答案)2013.doc

    java笔试经典(题及答案)2013.doc Java笔试经典(基础部分及答案和分析)1.一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制?7答:可以包括多个 ...

  2. java笔试题大全带答案_java笔试题大全带答案经典11题

    java笔试题大全带答案(经典11题) 1.不通过构造函数也能创建对象吗() A. 是 B. 否 分析:答案:A Java创建对象的几种方式(重要): (1) 用new语句创建对象,这是最常见的创建对 ...

  3. java从入门到精通教程_Java从入门到精通全套教程

    Java从入门到精通全套教程视频简介: 随着电脑网络的飞速发展,对现代计算机软件人才的要求越来越高.既要求他们横向掌握多门主流的编程语言,又需要同时至少对1-2门编程技术有深刻的认知.特此,星火视频为 ...

  4. java从入门到精通教程_Java从入门到精通小白教程

    Java从入门到精通小白教程,是小编为大家找到的一套非常不错的java编程学习实战资料,是专业版的学习工具书,它的主要作用是帮助用户进行全面基础学习和进阶准备,是十分靠谱的教程!希望大家好好学习,一起 ...

  5. java初学编程题及答案_Java 入门编程题答案记录(记录)

    输入格式: 首先,你会读到若干个城市的名字.每个名字都只是一个英文单词,中间不含空格或其他符号.当读到名字为"###"(三个#号)时,表示城市名字输入结束,###并不是一个城市的名 ...

  6. python从入门到精通清华_java从入门到精通(第5版)+python从入门到精通+c语言从入门到精通 全3册 清华大学出版社...

    <JAVA从入门到精通(第5版)> <Java从入门到精通(第5版)>从初学者角度出发,通过通俗易懂的语言.丰富多彩的实例,详细介绍了使用Java语言进行程序开发需要掌握的知识 ...

  7. java第二版课后题答案_Java语言程序设计第2版第16章 课后习题答案

    <Java语言程序设计第2版第16章 课后习题答案>由会员分享,可在线阅读,更多相关<Java语言程序设计第2版第16章 课后习题答案(62页珍藏版)>请在人人文库网上搜索. ...

  8. java语言程序设计第六章答案_Java语言程序设计(一)课后习题第六章(附答案)

    六.重载与多态 1.判断:接口中的所有方法都没有被实现.() 2.方法重载是指 ( ) A.两个或两个以上的方法取相同的方法名,但形参的个数或类型不同 B.两个以上的方法取相同的名字和具有相同的参数个 ...

  9. java期末考试卷及答案_java期末考试试卷及答案1

    本科java程序设计期末考试试卷 <Java 程序设计>期末考试试卷 第 1 页 共 9 页 学年 学期期末考试卷 卷 课程 <Java 程序设计> 考试时间: 120 分钟 ...

  10. java大学教程习题答案_Java程序设计大学教程:习题解答与课程设计

    前言 计算机程序设计课程既是一门理论课又是一门实践课,除了要在课堂学习程序设计的原理和方法,掌握程序设计语言的语法知识和编程技能外,还要进行大量的课外练习和实际操作,以达到熟悉掌握所学知识,培养应用能 ...

最新文章

  1. 安装Nginx的方法教程
  2. simple-spring-memcached统一缓存的使用实例4
  3. java ee 3.0_初识JavaEE 6 的 Servlet3.0
  4. 【Python】20个Pandas数据实战案例,干货多多
  5. 创建一个QT for Android的传感器应用应用程序(摘自笔者2015年将出的《QT5权威指南》,本文为试读篇)
  6. PowerDesigner提示This data item is already used in a primary identifier.的处理
  7. 使用Spring MVC开发Restful Web服务
  8. (三)Mybatis总结之动态sql
  9. 小白系列:修改美化pycharm主题
  10. 自动化运维平台-OpManager
  11. html中多一条黑线,Word页面中上下各有一条黑线怎样去掉?
  12. 网站在线工具查询链接收录与优化文章收录情况
  13. 鲁大师7月新机性能/流畅榜:性能跑分突破123万!
  14. 孤独星球android app,孤独星球免费版
  15. DNS服务器详解(端口占用与记录类型)
  16. 一个游戏中玩家总经验值达到200就可以到达2级,达到400可以升到3级,达到600可升4级,达到800可升5级依此类推(玩家新创建的角色为0经验1级)。游戏中有一种超级经验丹,玩家1级的时候使用超级经
  17. respond_to 和 respond_with
  18. Abaqus GUI程序开发之常用控件使用方法(八):快捷键设置
  19. rnss和rdss的应用_北斗RNSS/RDSS多模手持终端设计与实现
  20. (转)日语自我介绍大全

热门文章

  1. 自动格式化SQL工具推荐
  2. Win10离线 安装.net frame3.5
  3. 2020年30种最佳的免费网页爬虫软件
  4. 如何在Java语言编程中,如何输入一个char型字符
  5. 凸包算法 Matlab实现
  6. wer 流程图编程_WER机器人搭建学习实操练习
  7. 《软件方法》书中自测题大全-题目全文+分卷自测
  8. 激光打标机金橙子软件画出五角星最简单方法图解
  9. python怎么用散点图_怎么用Python画散点图
  10. Windows PowerShell | 错误: 740 需要提升权限才能运行 DISM