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. 輸入兩個非負整數(shù)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("請輸入兩個非負整數(shù): ");
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. 輸入一個數(shù)字判定是不是回文素數(shù)(回文素數(shù)是從左向右和從右向左讀都一樣的素數(shù))蟹地,例如:
輸入: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("請輸入一個數(shù): ");
int num = input.nextInt();
if (isPrime(num) && isPalindrome(num)) {
System.out.println("是回文素數(shù)");
}
else {
System.out.println("不是回文素數(shù)");
}
input.close();
}
}
7. 編寫一個方法傳入兩個正整數(shù)返回其最小公倍數(shù)。
方法原型: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("請輸入兩個正整數(shù): ");
int x = input.nextInt();
int y = input.nextInt();
System.out.println("最小公倍數(shù)是:" + lcm(x, y));
input.close();
}
}
8. 編寫一個方法實現(xiàn)將非負整數(shù)轉(zhuǎn)成二進制字符串藤为。
方法原型: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("請輸入一個數(shù): ");
int num = input.nextInt();
System.out.println(toBinaryString(num));
input.close();
}
}
9.編寫一個方法檢查數(shù)據(jù)中的元素能否構(gòu)成等差數(shù)列怪与。
方法原型: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. 編寫一個方法實現(xiàn)數(shù)組的反轉(zhuǎn),例如:
{ "hello", "good", "yes", "no" } 反轉(zhuǎn)之后變成 { "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. 編寫一個方法從數(shù)組中找出最大的元素缅疟。
方法原型: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. 編寫一個方法從數(shù)組中找出第二大的元素分别。
方法原型: 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. 寫一個類描述銀行卡遍愿,提供存款、取款和轉(zhuǎn)賬的操作耘斩。
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. 用面向?qū)ο蟮姆绞綄崿F(xiàn)人機猜拳游戲(用1-3的數(shù)字分別表示“剪刀”、“石頭”和“布”荚虚,計算機隨機產(chǎn)生1-3的數(shù)字表示所出的拳薛夜,人輸入1-3的數(shù)字表示所出的拳,出拳后顯示計算機和人出了什么拳以及勝負平的關(guān)系)版述。
游戲類:
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. 發(fā)揮自己的想象力用面向?qū)ο蟮姆绞侥M“龜兔賽跑”梯澜。
烏龜類:
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. 發(fā)揮自己的想象力用面向?qū)ο蟮姆绞侥M“學(xué)生找槍手代考”。
**
學(xué)生類:
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. 寫一個方法實現(xiàn)文件備份的功能晚伙,備份文件跟原始文件在同一路徑下,文件名是原始文件名加上.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基礎(chǔ).jpg");
System.out.println("備份成功.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
19. 基于TCP創(chuàng)建一個多線程的天氣查詢服務(wù)器,客戶端輸入城市代碼(例如:CD表示成都恢恼、BJ表示北京)民傻,服務(wù)器向客戶端發(fā)送對應(yīng)城市的天氣信息,服務(wù)器通過一個映射容器保存多個城市的天氣信息(天氣信息自行設(shè)定)场斑,其中城市代碼作為鍵天氣信息作為值漓踢,如果容器中沒有要查詢的城市則向客戶端返回友好的提示信息。
服務(wù)端:
public class Server {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Map<String, String> weatherInfo = new HashMap<>();
weatherInfo.put("CD", "溫度:28 晴轉(zhuǎn)多云");
weatherInfo.put("BJ", "溫度:10 雷電雨");
try (ServerSocket server = new ServerSocket(1234)) {
System.out.println("服務(wù)器已經(jīng)啟動...");
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 = "沒有找到對應(yīng)城市的天氣預(yù)報,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);
}
}