java 期末复习题目练习

1 打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153 是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

package one;
public class Shuixianhua {
	public static void main(String[] args) {
		System.out.println("所有的水仙花数:");
		for (int i = 100; i < 1000; i++) {
			int ge,shi,bai;
			bai=i/100;
			shi=(i-100*bai)/10;
			ge=i-bai*100-shi*10;
			if(i==bai*bai*bai+shi*shi*shi+ge*ge*ge){
				System.out.println(i+"");
			}
		}	
	}
}

java 期末复习题目练习_第1张图片

2 建立一个长度为9的数组,随机为该数组分配九个0~100间的随机数作为数组元素,并顺序打印数组元素;然后实现数组反转,并打印反转后的数组元素。

package two;
import java.util.Random;
public class RandomNum {
	public static void main(String[] args) {

		int[] a=new int[9];
		for (int i = 0; i < a.length; i++) {
			a[i]=(int)(Math.random()*100)+1;
		}
		System.out.println("顺序输出随机数:");
		for (int i = 0; i < a.length; i++) {
			System.out.println("a["+i+"]="+a[i]);
		}
		
		for (int i = 0; i < a.length/2; i++) {
			int temp=a[i];
			a[i]=a[a.length-i-1];
			a[a.length-i-1]=temp;
		}
		System.out.println("数组反转后:");
		for (int i = 0; i < a.length; i++) {
			System.out.println("a["+i+"]="+a[i]);
		}
	}

}

java 期末复习题目练习_第2张图片

3 编写程序模拟体操比赛选手成绩的计算方法。首先输入五位评委各自的打分(满分100分),去掉一个最高分、去掉一个最低分后求平均分(保留小数点后两位)作为选手的最终成绩并输出。

package three;

import java.util.Scanner;

public class Score {

	public static void main(String[] args) {
		System.out.println("请各评委输入8号选手的成绩:");
		Scanner in = new Scanner(System.in);
		double a[] = new double[5];
		for(int i=0; i<5; i++){
			a[i]=in.nextDouble();
		}
		System.out.println("五位评委分别打分为:");
		for(int i=0; i<5; i++)
			System.out.print("  "+a[i]);
		System.out.println();
		double avg=0;
		//对数组的值进行冒泡排序
		for (int i = 1; i < a.length; i++) {
			for (int j = 0; j < a.length-i; j++) {
				if (a[j]>a[j+1]) {
					double temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}
		for(int i=0; i<5; i++)
			avg+=a[i];
		System.out.println("8号选手的最终得分是:"+((avg-a[a.length-1]-a[0])/5));

	}
	

}

java 期末复习题目练习_第3张图片

4 编写一个应用程序,用户分别从两个文本框输入学生的姓名和分数,程序按成绩排序将这些学生的姓名和分数显示在一个文本区中。
程序以及运行效果如图:

package four;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class StudentFrame extends JFrame{
	JPanel pl;
	JLabel name, score;
	JTextField inputName, inputScore;
	JButton button;
	JScrollPane sp;
	JTextArea showArea;
	TreeSet treeSet;
	
	StudentFrame(String title){
		super(title);
		treeSet = new TreeSet();
		
		pl = new JPanel();
		name = new JLabel("姓名");
		score = new JLabel("成绩");
		inputName = new JTextField(5);
		inputScore = new JTextField(5);
		button = new JButton("确定");
		button.addActionListener(new MyListener());
		pl.add(name);
		pl.add(inputName);
		pl.add(score);
		pl.add(inputScore);
		pl.add(button);
		
		showArea = new JTextArea();
		sp = new JScrollPane(showArea);
		
		add(pl, BorderLayout.NORTH);
		add(sp, BorderLayout.CENTER);
		setSize(400,300);
		setVisible(true);
		validate();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
	
class MyListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			String name = inputName.getText();
			int score = 0;
			try{
				score = Integer.parseInt(inputScore.getText().trim());
				if(name.length()>0){
					Student stu = new Student(name, score);
					treeSet.add(stu);
					show(treeSet);
				}
			}catch(NumberFormatException nfe){
				inputScore.setText("请输入数字字符");
			}
		}
		public void show(TreeSet tree){
			showArea.setText(null);
			Iterator it = treeSet.iterator();
			while(it.hasNext()){
				Student stu = it.next();
				showArea.append("姓名:"+stu.getName()+"    成绩:"+stu.getScore()+"\n");
			}
		}
	}
	
	public static void main(String[] args) {
		new StudentFrame("学生成绩排序");

	}

}
class Student implements Comparable{
	String name;
	int score;
	Student(String name, int score){
		this.name = name;
		this.score = score;
	}
	public int getScore(){
		return score;
	}
	public String getName(){
		return name;
	}
	public int compareTo(Object b){
		Student st = (Student)b;
		int m = this.score - st.getScore();
		if (m!=0)
			return m;
		else 
			return 1;
	}
}

java 期末复习题目练习_第4张图片
5 有10个U盘,有两个重要的属性:价格和容量。编写一个应用程序,使用TreeMap<>类,分别按照价格和容量排序输出10个U盘的详细信息。

package five;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public class UDisk {
	int amount;
	double price;
	UDisk(int amount, double price){
		this.amount = amount;
		this.price = price;
	}
}

class UKey implements Comparable{
	double key = 0;
	UKey(double key){
		this.key = key;
	}
	public int compareTo(Object b){
		UKey bb = (UKey)b;
		if(this.key == bb.key)
			return -1;
		else
			return (int)((this.key-bb.key)*1000);
	}
}


class E{
	public static void main(String[] args) {
		TreeMap treemap = new TreeMap();
		int amount[] = {1, 2, 4, 8, 16, 32};
		double price[] = {25, 18, 32, 80, 64, 120};
		
		UDisk ud[] = new UDisk[6];
		for(int i=0; i c = treemap.values();
		Iterator it = c.iterator();
		while(it.hasNext()){
			UDisk d = it.next();
			System.out.println("容量"+d.amount+"GB,"+d.price+"元");
		}
		treemap.clear();
		System.out.println("--------------------------------------");
		
		for(int i=0; i

java 期末复习题目练习_第5张图片
6 编写一个简易计算器,有一个标题为“简易计算器”的窗口。设计 “+”、“-”、“*”、“/”四种运算,另外,窗口中还有三个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。要求处理NumberFormatException异常。程序运行效果如下图:

package six;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
	JTextField text1, text2, text3;
	JRadioButton btnAdd, btnSub, btnMul, btnDiv;
	ButtonGroup bg;
	JLabel num1, num2, result;
	JButton solve;
	Box base, boxH1, boxH2, boxH3, boxH4;
	
	public Calculator(String name){
		super(name);
		setLayout(new FlowLayout());
		text1 = new JTextField(10);
		text2 = new JTextField(10);
		text3 = new JTextField(10);
		btnAdd = new JRadioButton("+");
		btnSub = new JRadioButton("-");
		btnMul = new JRadioButton("*");
		btnDiv = new JRadioButton("/");
		num1 = new JLabel("数一");
		num2 = new JLabel("数二");
		result = new JLabel("结果");
		solve = new JButton("=");
		solve.addActionListener(this);
		bg = new ButtonGroup();
		bg.add(btnAdd);
		bg.add(btnSub);
		bg.add(btnMul);
		bg.add(btnDiv);
				
		boxH1 = Box.createHorizontalBox();
		boxH1.add(num1);
		boxH1.add(Box.createHorizontalStrut(30));
		boxH1.add(text1);
		boxH2 = Box.createHorizontalBox();
		boxH2.add(btnAdd);
		boxH2.add(btnSub);
		boxH2.add(btnMul);
		boxH2.add(btnDiv);
		boxH3 = Box.createHorizontalBox();
		boxH3.add(num2);
		boxH3.add(Box.createHorizontalStrut(30));
		boxH3.add(text2);
		boxH4 = Box.createHorizontalBox();
		boxH4.add(result);
		boxH4.add(Box.createHorizontalStrut(30));
		boxH4.add(text3);
		base = Box.createVerticalBox();
		base.add(boxH1);
		base.add(Box.createVerticalStrut(25));
		base.add(boxH2);
		base.add(Box.createVerticalStrut(25));
		base.add(boxH3);
		base.add(Box.createVerticalStrut(25));
		base.add(solve);
		base.add(Box.createVerticalStrut(25));
		base.add(boxH4);
		add(base);
		
		setSize(300, 320);
		setVisible(true);
		validate();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent e){
		double n = 0;
		double n1,n2;
		try{
				n1=Double.parseDouble(text1.getText());
				n2=Double.parseDouble(text2.getText());
				if(btnAdd.isSelected())
					n = n1+n2;
				else if(btnSub.isSelected())
					n = n1-n2;
				else if(btnMul.isSelected())
					n = n1*n2;
				else if(btnDiv.isSelected())
					n = n1/n2;
				text3.setText(String.valueOf(n));
				
		}catch(NumberFormatException nfe){
				text3.setText("请输入数字字符");
		}
		
	}
	
	public static void main(String args[]){
		new Calculator("简易计算器");
	}

}

java 期末复习题目练习_第6张图片
7 请写一个简易计时器。单击“开始”按钮启动计时器,并将计时时间显示在文本框中;单击“暂停”按钮暂停计时器;单击“继续”按钮重新启动计时器。程序运行效果如下图:

package seven;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MyTimer extends JFrame implements ActionListener {
	JTextField text;
	JButton bStart, bStop, bContinue;
	Timer time;
	int n = 0;
	
	MyTimer(String name){
		super(name);
		time = new Timer(1000, this);
		text = new JTextField(15);
		bStart = new JButton("开始");
		bStop = new JButton("暂停");
		bContinue = new JButton("继续");
		bStart.addActionListener(this);
		bStop.addActionListener(this);
		bContinue.addActionListener(this);
		setLayout(new FlowLayout());
		add(bStart);
		add(bStop);
		add(bContinue);
		add(text);
		
		setSize(300, 120);
		setVisible(true);
		validate();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent e){
		if(e.getSource()==time){
			n = n + 1;
			text.setText("计时:"+ n +"秒");
		}
		else if(e.getSource()==bStart){
			n = 0;
			time.start();
		}
			
		else if(e.getSource()==bStop)
			time.stop();
		else if(e.getSource()==bContinue)
			time.restart();
	}
	public static void main(String[] args) {
		new MyTimer("简易计时器");

	}

}

java 期末复习题目练习_第7张图片
8 编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次通过山洞的人名。提示:利用线程同步机制,过山洞用一条输出语句表示,该输出语句打印输出当前过山洞的人名,每个人过山洞对应一个线程,哪个线程执行这条输出语句,就表示哪个人过山洞。

package eight;

import java.util.Random;

public class PassCave implements Runnable{

	public void run() {
		synchronized (this) {
			System.out.println(Thread.currentThread().getName()+"正在通过山洞");
			try{
				Thread.sleep(2000);
			}catch(InterruptedException ie){
				ie.printStackTrace();
			}
		}
		
	}
	public static String getRandomString(int length) { //length表示生成字符串的长度
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < length; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	 }   

	public static void main(String[] args) {
		PassCave pc = new PassCave();
		Thread th[] = new Thread[10];
		for(int i=0; i<10; i++){
			th[i] = new Thread(pc);
			th[i].setName(getRandomString(5));
			th[i].start();			
		}

	}

}

java 期末复习题目练习_第8张图片
9 用两个线程玩猜数字游戏,第一个线程负责随机给出1~100之间的一个整数,第二个线程负责猜出这个数。要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。第一个线程设置好猜测数之后,两个线程还要相互等待,其原则是:第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测,如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。

package nine;

public class GuessNumber {
	public static void main(String args[]){
		Number number = new Number();
		number.giveNumberThread.start();
		number.guessNumberThread.start();
	}
}

class Number implements Runnable{
	final int SMALLER = -1, LARGER = 1, SUCCESS = 8;
	int realNumber, guessNumber, min = 0, max = 100, message = SMALLER;
	boolean pleaseGuess = false, isGiveNumber = false;
	Thread giveNumberThread, guessNumberThread;
	
	Number(){
		giveNumberThread = new Thread(this);
		guessNumberThread = new Thread(this);
	}
	
	public void run(){
		for(int count =1; true; count++){
			setMessage(count);
			if(message == SUCCESS)
				return;
		}
	}
	
	public synchronized void setMessage(int count){
		if(Thread.currentThread() == giveNumberThread && isGiveNumber == false){
			realNumber = (int)(Math.random()*100)+1;
			System.out.println("随机给你一个1至100之间的数,猜猜是多少?");
			isGiveNumber = true;
			pleaseGuess = true;
		}
		if(Thread.currentThread() == giveNumberThread){
			while(pleaseGuess == true)
				try{
					wait();       //让出CPU使用权,让另一个线程开始猜数
				}catch(InterruptedException e){ }
			
			if(realNumber > guessNumber){
				message = SMALLER;
				System.out.println("你猜小了!");
			}
			else if(realNumber < guessNumber){
				message = LARGER;
				System.out.println("你猜大了!");
			}
			else {
				message = SUCCESS;
				System.out.println("恭喜,你猜对了!");
			}
			pleaseGuess = true;
		}
		if(Thread.currentThread() == guessNumberThread && isGiveNumber == true){
			while(pleaseGuess == false)
				try{
					wait();       //让出CPU使用权,让另一个线程开始猜数
				}catch(InterruptedException e){ }
			if(message == SMALLER){
				min = guessNumber;
				guessNumber = (min + max)/2;
				System.out.println("我第"+count+"次猜这个数是"+guessNumber);
			}
			else if(message == LARGER){
				max = guessNumber;
				guessNumber = (min + max)/2;
				System.out.println("我第"+count+"次猜这个数是"+guessNumber);
			}
			pleaseGuess = false;
		}
		notifyAll();
	}
}

java 期末复习题目练习_第9张图片
10 在电视节目中经常看见主持人提出的问题,并要求考试者在限定时间内回答问题。这里由程序提出问题,用户回答问题。问题保存在test.txt中,test.txt的格式如下。
每个问题提供A、B、C、D四个选择(单项选择)。
两个问题之间是用减号(-)尾加前一问题的答案分隔(例如:----D----)。
使用GUI界面,增加一个辅助限制答题时间的计时器线程,该线程限制用户必须在10秒内回答问题,一旦超过10秒,将进入下一题。程序运行效果如下图:

package ten;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Exam extends JFrame implements ActionListener, ItemListener{
	File test;
	int MAX = 10;
	int maxTime = MAX, score = 0;
	javax.swing.Timer time;
	JTextArea showQuestion;
	JCheckBox choiceA, choiceB, choiceC, choiceD;
	JLabel showScore, showTime;
	String correctAnswer;
	JButton reStart;
	FileReader inOne;
	BufferedReader inTwo;
	Box base, boxH1, boxH2;
	
	Exam(String title){
		super(title);
		time = new javax.swing.Timer(1000, this);
		showQuestion = new JTextArea(2, 16);
		setLayout(new FlowLayout());
		showScore = new JLabel("分数"+score);
		showTime = new JLabel(" ");
		boxH1 = Box.createHorizontalBox();
		boxH1.add(showTime);
		boxH1.add(new JLabel("问题"));
		boxH1.add(showQuestion);
		choiceA = new JCheckBox("A");
		choiceB = new JCheckBox("B");
		choiceC = new JCheckBox("C");
		choiceD = new JCheckBox("D");
		choiceA.addItemListener(this);
		choiceB.addItemListener(this);
		choiceC.addItemListener(this);
		choiceD.addItemListener(this);
		boxH2 = Box.createHorizontalBox();
		boxH2.add(choiceA);
		boxH2.add(choiceB);
		boxH2.add(choiceC);
		boxH2.add(choiceD);
		boxH2.add(showScore);
		reStart = new JButton("再做一遍");
		reStart.setEnabled(false);
		reStart.addActionListener(this);
		boxH2.add(reStart);
		base = Box.createVerticalBox();
		base.add(boxH1);
		base.add(boxH2);
		add(base);
		setSize(400,200);
		setVisible(true);
		validate();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	
	public void setMAX(int n){
		MAX = n;
	}
	public void setTestFile(File f){
		test = f;
		score = 0;
		try{
			inOne = new FileReader(test);
			inTwo = new BufferedReader(inOne);
			readOneQuestion();
			reStart.setEnabled(false);
		}catch(IOException e){
			showQuestion.setText("没有选题");
		}		
	}
	public void readOneQuestion(){
		showQuestion.setText(null);
		try{
			String s = null;
			while((s=inTwo.readLine())!=null){
				if(!s.startsWith("-"))
					showQuestion.append("\n"+s);
				else{
					s = s.replaceAll("-", "");
					correctAnswer = s;
					break;
				}
			}
			time.start();
			if(s==null){
				inTwo.close();
				reStart.setEnabled(true);
				showQuestion.setText("题目完毕");
				time.stop();
			}
		}catch(IOException e){ }
	}
	
	public void itemStateChanged(ItemEvent e){
		JCheckBox box = (JCheckBox)e.getSource();
		String str = box.getText();
		boolean bOne = box.isSelected();
		boolean bTwo = str.compareToIgnoreCase(correctAnswer)==0;
		if(bOne && bTwo){
			score++;
			showScore.setText("分数"+score);
			time.stop();
			maxTime = MAX;
			readOneQuestion();
		}
		box.setSelected(false);
	}
	
	public void actionPerformed(ActionEvent e){
		if(e.getSource()==time){
			showTime.setText("剩:"+maxTime+"秒");
			maxTime--;
			if(maxTime<=0){
				maxTime = MAX;
				readOneQuestion();
			}
		}
		else if(e.getSource()==reStart)
			setTestFile(test);
	}
}

class Answer{
	public static void main(String[] args) {
		Exam win = new Exam("限时回答问题");
		win.setTestFile(new File("D:\\","test.txt"));
		win.setMAX(10);
	}
}

java 期末复习题目练习_第10张图片

你可能感兴趣的:(java)