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+"");
}
}
}
}
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]);
}
}
}
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));
}
}
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<Student> treeSet;
StudentFrame(String title){
super(title);
treeSet = new TreeSet<Student>();
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