1. 输入矩形的宽和高,输出其周长和面积,例如:
输入:5 10
输出:Perimeter=30.0, Area=50.0
public class Ex01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入矩形的宽和高: ");
double width = input.nextDouble();
double height = input.nextDouble();
System.out.printf("矩形的周长为: %.1f\n", (width + height) * 2);
System.out.printf("矩形的面积为: %.1f", width * height);
input.close();
}
}
2. 输入两个非负整数m和n,计算m的n次方,例如:
输入:5 3
输出:125
public class Ex02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m, n;
do {
System.out.print("请输入两个非负整数: ");
m = input.nextInt();
n = input.nextInt();
} while (m < 0 || n < 0);
System.out.printf("%d的%d次方等于: %d", m, n, (int) Math.pow(m, n));
input.close();
}
}
3. 打印1-10的立方表,格式如下所示:
1 1
2 8
3 27
4 64
5 125
……
public class Ex03 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.printf("%d\t%d\n", i, (int) Math.pow(i, 3));
}
}
}
4. 输入年月日输出该日期是这一年的第几天,例如:
输入:2016 11 28
输出:333
public class Ex04 {
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? true : false;
}
public static int dayOfMonth (int month, int year) {
int days;
switch (month) {
case 2:
if (isLeapYear(year)) {
days = 29;
}
else {
days = 28;
}
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
}
return days;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年、月、日: ");
int year = input.nextInt();
int month = input.nextInt();
int day = input.nextInt();
int total = day;
for (int i = 1; i < month; i++) {
total += dayOfMonth(i, year);
}
System.out.printf("%d年%d月%d日是这一年的第%d天", year, month, day, total);
input.close();
}
}
5. 输入两组年月日,计算两个日期相差多少天,例如:
输入:2016 1 1 2017 1 1
输出:366
public class Ex05 {
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? true : false;
}
public static int dayOfMonth (int month, int year) {
int days;
switch (month) {
case 2:
if (isLeapYear(year)) {
days = 29;
}
else {
days = 28;
}
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
}
return days;
}
public static int totalOfDays(int year, int month, int day) {
int total = 0;
for (int i = 1; i < year; i++) {
if (isLeapYear(i)) {
total += 366;
}
else {
total += 365;
}
}
for (int i = 1; i < month; i++) {
total += dayOfMonth(i, year);
}
total += day;
return total;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入两组年、月、日: ");
int year1 = input.nextInt();
int month1 = input.nextInt();
int day1 = input.nextInt();
int year2 = input.nextInt();
int month2 = input.nextInt();
int day2 = input.nextInt();
int dif = totalOfDays(year1, month1, day1) - totalOfDays(year2, month2, day2);
System.out.printf("%d年%d月%d日和%d年%d月%d日相差了%d天", year1, month1, day1,
year2, month2, day2, Math.abs(dif));
input.close();
}
}
6. 输入一个数字判定是不是回文素数(回文素数是从左向右和从右向左读都一样的素数),例如:
输入:141
输出:否
输入:11
输出:是
public class Ex06 {
public static boolean isPrime(int num) {
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
public static boolean isPalindrome(int num) {
boolean result = true;
StringBuilder sb = new StringBuilder(num);
if (!sb.equals(sb.reverse())) {
result = false;
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个数: ");
int num = input.nextInt();
if (isPrime(num) && isPalindrome(num)) {
System.out.println("是回文素数");
}
else {
System.out.println("不是回文素数");
}
input.close();
}
}
7. 编写一个方法传入两个正整数返回其最小公倍数。
方法原型:public static int lcm(int x, int y)
public class Ex07 {
public static int lcm(int x, int y) {
int min = x < y ? x : y;
int result = 0;
for (int i = min; i > 0; i--) {
if (x % i == 0 && y % i == 0) {
result = i;
break;
}
}
return (x * y) / result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入两个正整数: ");
int x = input.nextInt();
int y = input.nextInt();
System.out.println("最小公倍数是:" + lcm(x, y));
input.close();
}
}
8. 编写一个方法实现将非负整数转成二进制字符串。
方法原型:public static String toBinaryString(int num)
public class Ex08 {
public static String toBinaryString(int num) {
StringBuilder sb = new StringBuilder();
while (num > 0) {
if (num % 2 == 0) {
sb.append(0);
}
else {
sb.append(1);
}
num /= 2;
}
return sb.reverse().toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个数: ");
int num = input.nextInt();
System.out.println(toBinaryString(num));
input.close();
}
}
9.编写一个方法检查数据中的元素能否构成等差数列。
方法原型:public static boolean isAP(int[] array)
public class Ex09 {
public static boolean isAP(int[] array) {
boolean isAP = true;
int n = array[1] - array[0];
for (int i = 1; i < array.length - 1; i++) {
if ((array[i + 1] - array[i]) != n) {
isAP = false;
break;
}
}
return isAP;
}
public static void main(String[] args) {
int a[] = {-2, -4, -6, -8};
if (isAP(a)) {
System.out.println("是");
}
else {
System.out.println("否");
}
}
}
10. 编写一个方法实现数组的反转,例如:
{ "hello", "good", "yes", "no" } 反转之后变成 { "no", "yes", "good", "hello" }
方法原型:public static <T> void reverse(T[] array)
public class Ex10 {
public static <T> void reverse(T[] array) {
for (int i = 0, len = array.length; i < len / 2; i++) {
T temp = array[i];
array[i] = array[len - i - 1];
array[len - i - 1] = temp;
}
}
public static void main(String[] args) {
String[] a = { "hello", "good", "yes", "no" };
reverse(a);
for (String str : a) {
System.out.println(str);
}
}
}
11. 编写一个方法从数组中找出最大的元素。
方法原型:public static <T extends Comparable<T>> T maxOfArray(T[] array)
public class Ex11 {
public static <T extends Comparable<T>> T maxOfArray(T[] array) {
T max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i].compareTo(max) > 0) {
max = array[i];
}
}
return max;
}
public static void main(String[] args) {
String[] a = { "a", "b", "c", "d" };
System.out.println(maxOfArray(a));
}
}
12. 编写一个方法从数组中找出第二大的元素。
方法原型: public static <T> T secondaryMaxOfArray(T[] array, Comparator<T> comp)
public class Ex12 {
public static <T> T secondaryMaxOfArray(T[] array, Comparator<T> comp) {
T max = array[0];
T secondaryMax = array[1];
for (int i = 0; i < array.length; i++) {
if (comp.compare(array[i], max) > 0) {
secondaryMax = max;
max = array[i];
}
else if (comp.compare(array[i], max) < 0 && comp.compare(array[i], secondaryMax) > 0) {
secondaryMax = array[i];
}
}
return secondaryMax;
}
public static void main(String[] args) {
String[] a = { "a", "b", "f", "d", "e" };
System.out.println(secondaryMaxOfArray(a, new Comparator<String>() {
@Override
public int compare(String o1,String o2) {
return o1.compareTo(o2);
}
}));
}
}
13. 写一个类描述银行卡,提供存款、取款和转账的操作。
public class BankCard {
private String id;
private String password;
private double balance;
public BankCard(String id) {
this.id = id;
this.password = "8888888";
this.balance = 0;
}
public boolean isValid(String password) {
return this.password.equals(password);
}
public void deposit(double money) {
balance += money;
}
public void withdraw(double money) {
if (money < balance) {
balance -= money;
}
}
public void transfer(BankCard bankCard, double money) {
if (money < balance) {
balance -= money;
bankCard.setBalance(bankCard.getBalance() + money);
}
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setPassword(String password) {
this.password = password;
}
public String getId() {
return id;
}
}
14. 写一个类描述计时器(可以显示时、分、秒),提供显示时间和倒计时的操作。
计时器类:
public class Timer {
private int second;
private int minute;
private int hour;
public Timer(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
public String show() {
return String.format("%02d时:%02d分:%02d秒", hour, minute, second);
}
public void running() {
if (second > 0) {
second -= 1;
}
else {
if (minute > 0) {
second = 59;
minute -= 1;
}
else {
if (hour > 0) {
minute = 59;
hour -= 1;
}
}
}
}
public boolean isEnd() {
return hour == 0 && minute == 0 && second == 0 ? true : false;
}
}
测试:
public class Ex14 {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer(1, 23, 50);
while (!timer.isEnd()) {
System.out.println(timer.show());
timer.running();
Thread.sleep(1000);
}
}
}
15. 用面向对象的方式实现人机猜拳游戏(用1-3的数字分别表示“剪刀”、“石头”和“布”,计算机随机产生1-3的数字表示所出的拳,人输入1-3的数字表示所出的拳,出拳后显示计算机和人出了什么拳以及胜负平的关系)。
游戏类:
public class FingerGame {
private int robotNum;
private String result;
private String[] fist = {"剪刀", "石头", "布"};
private String gameInfo;
public FingerGame() {
reset();
}
public void game(int playerNum) {
gameInfo = info(playerNum);
if (playerNum == robotNum) {
result = "双方平手.";
}
else {
boolean isVictory = true;
if ((playerNum - robotNum) % 2 == 0) {
isVictory = playerNum > robotNum ? false : true;
}
else {
isVictory = playerNum > robotNum ? true : false;
}
result = isVictory ? "玩家胜." : "电脑胜";
}
}
public String info(int playerNum) {
return String.format("玩家出拳: %s 电脑出拳: %s", fist[playerNum - 1], fist[robotNum - 1]);
}
public void reset() {
this.robotNum = (int) (Math.random() * 3 + 1);
}
public int getRobotNum() {
return robotNum;
}
public String getResult() {
return result;
}
public String getGameInfo() {
return gameInfo;
}
}
测试:
public class Ex15 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入你要出的拳: ");
int playerNum = input.nextInt();
FingerGame game = new FingerGame();
game.game(playerNum);
System.out.println(game.getGameInfo());
System.out.println(game.getResult());
input.close();
}
}
16. 发挥自己的想象力用面向对象的方式模拟“龟兔赛跑”。
乌龟类:
public class Tortoise {
private String name;
private double speed;
public Tortoise(String name) {
this.name = name;
this.speed = 2;
}
public void run() {
System.out.println("乌龟正在努力赛跑...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
}
兔子类:
public class Rabbit {
private String name;
private double speed;
public Rabbit(String name) {
this.name = name;
this.speed = 10;
}
public void run() {
System.out.println("兔子正在赛跑...");
}
public void inLazy() {
System.out.println("兔子在偷懒睡觉...");
this.speed = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
}
赛跑游戏类:
public class Race {
private int distance;
private Tortoise tortoise;
private Rabbit rabbit;
public Race(int distance, Tortoise tortoise, Rabbit rabbit) {
this.distance = distance;
this.tortoise = tortoise;
this.rabbit = rabbit;
}
public void match() throws InterruptedException {
int tDistance = distance;
int rDistance = distance;
while (tDistance > 0 && rDistance > 0) {
Thread.sleep(1000);
tDistance -= tortoise.getSpeed();
tortoise.run();
System.out.println("乌龟还有" + tDistance + "米");
if (rDistance > distance / 2) {
rDistance -= rabbit.getSpeed();
rabbit.run();
System.out.println("兔子还有" + rDistance + "米");
}
else {
rabbit.inLazy();
}
}
if (tDistance == 0) {
System.out.println("乌龟胜利.");
}
else if (rDistance == 0) {
System.out.println("兔子胜利.");
}
}
}
测试:
public class Ex16 {
public static void main(String[] args) {
Tortoise tortoise = new Tortoise("乌龟");
Rabbit rabbit = new Rabbit("兔子");
Race race = new Race(400, tortoise, rabbit);
try {
race.match();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
**17. 发挥自己的想象力用面向对象的方式模拟“学生找枪手代考”。
**
学生类:
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void test() {
System.out.println(name + "要考试,他要找人帮忙代考");
}
public void findGunner(Gunner gunner) {
gunner.generationOfTest(this);
}
public String getName() {
return name;
}
}
枪手类:
public class Gunner {
private String name;
public Gunner(String name) {
this.name = name;
}
public void generationOfTest(Student student) {
System.out.println(name + "帮" + student.getName() + "代考.");
}
}
测试类:
public class Ex17 {
public static void main(String[] args) {
Student student = new Student("小明");
Gunner gunner = new Gunner("王麻子");
student.test();
student.findGunner(gunner);
}
}
18. 写一个方法实现文件备份的功能,备份文件跟原始文件在同一路径下,文件名是原始文件名加上.bak后缀,不能使用Files工具类。
方法原型:
public static void backupFile(String source) throws IOException
public static void backupFile(File file) throws IOException
public class Ex18 {
public static void backupFile(String source) throws IOException {
InputStream in = new FileInputStream(source);
String newFileName = source.split("\\.")[0] + ".bak";
OutputStream out = new FileOutputStream(newFileName);
byte[] buf = new byte[1024];
int total;
while ((total = in.read(buf)) != -1) {
out.write(buf, 0, total);
}
in.close();
out.close();
}
public static void backupFile(File file) throws IOException {
String source = file.getAbsolutePath();
backupFile(source);
}
public static void main(String[] args) {
try {
backupFile("C:/Java基础.jpg");
System.out.println("备份成功.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
19. 基于TCP创建一个多线程的天气查询服务器,客户端输入城市代码(例如:CD表示成都、BJ表示北京),服务器向客户端发送对应城市的天气信息,服务器通过一个映射容器保存多个城市的天气信息(天气信息自行设定),其中城市代码作为键天气信息作为值,如果容器中没有要查询的城市则向客户端返回友好的提示信息。
服务端:
public class Server {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Map<String, String> weatherInfo = new HashMap<>();
weatherInfo.put("CD", "温度:28 晴转多云");
weatherInfo.put("BJ", "温度:10 雷电雨");
try (ServerSocket server = new ServerSocket(1234)) {
System.out.println("服务器已经启动...");
boolean isRunning = true;
while (isRunning) {
Socket client = server.accept();
service.execute(() -> {
InputStream in;
try {
in = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
OutputStream out = client.getOutputStream();
PrintStream ps = new PrintStream(out);
String str;
String info;
while ((str = br.readLine()) != null) {
if (str.equals("bye")) {
client.close();
break;
}
if (weatherInfo.containsKey(str)) {
info = weatherInfo.get(str);
}
else {
info = "没有找到对应城市的天气预报,sry.";
}
ps.println(info);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
public class Client {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try (Socket client = new Socket("127.0.0.1", 1234)) {
System.out.print("请输入查询的城市: ");
String cityName;
OutputStream out = client.getOutputStream();
PrintStream ps = new PrintStream(out);
InputStream in = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while (!(cityName = scanner.nextLine()).equals("bye")) {
ps.println(cityName);
System.out.println(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
scanner.close();
}
}
20. 用提供的素材制作一个“奔跑者”的动画。
窗口类:
@SuppressWarnings("serial")
public class MyFrame extends JFrame {
private Image runnerImage;
private int m;
public MyFrame() {
this.setTitle("动画");
this.setSize(700, 300);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
ClassLoader classLoader = this.getClass().getClassLoader();
String str = "Runner/runner";
try {
runnerImage = ImageIO.read(classLoader.getResourceAsStream(str + 0 + ".jpg"));
repaint();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(() -> {
while (true) {
for (int i = 0; i < 6; i++) {
try {
runnerImage = ImageIO.read(classLoader
.getResourceAsStream(str + i + ".jpg"));
if (m < 700) {
m += 50;
}
else {
m = 0;
}
repaint();
Thread.sleep(100);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(runnerImage, m, 100, null);
}
}
测试:
public class Ex20 {
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}