引言

一味地追求理解概念不如 Show Me The Code,本篇博文收集了网络上常见的 Java 基础阶段编程题目
博文意在巩固基本概念,提高自己运用代码解决问题的能力以及帮助自己理解概念的深层内涵
挑选一些比较有趣的题目及比较有启发的解法

显示当前时间

/*
* 显示当前时间
**/
@Test
public void showCurrentTime() {
long totalMilliseconds = System.currentTimeMillis();
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
long currentHour = (totalHours + 8) % 24;

System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond);
}

判断闰年

/*
* 判断闰年
**/
@Test
public void leapYear() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

System.out.println(year + " is a leap year? " + isLeapYear);
}

计算生肖

/*
* 计算生肖
**/
@Test
public void chineseZodiac() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();

switch (year % 12) {
case 0: System.out.println("猴"); break;
case 1: System.out.println("鸡"); break;
case 2: System.out.println("狗"); break;
case 3: System.out.println("猪"); break;
case 4: System.out.println("鼠"); break;
case 5: System.out.println("牛"); break;
case 6: System.out.println("虎"); break;
case 7: System.out.println("兔"); break;
case 8: System.out.println("龙"); break;
case 9: System.out.println("蛇"); break;
case 10: System.out.println("马"); break;
case 11: System.out.println("羊");
}
}

99 乘法表

/*
* 99 乘法表
**/
@Test
public void multiplicationTable() {
System.out.println(" Multiplication Table");
System.out.print(" ");
for (int j = 1; j <= 9; ++j) {
System.out.print(" " + j);
}
System.out.println("\n----------------------------------------");
for (int i = 1; i <= 9; ++i) {
System.out.print(i + " | ");
for (int j = 1; j <= 9; ++j) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}

找出两个正整数的最大公约数

/*
* 找出两个正整数的最大公约数
**/
@Test
public void greatestCommonDivisor() {
Scanner input = new Scanner(System.in);
System.out.print("Enter first integer: ");
long n1 = input.nextLong();
System.out.print("Enter second integer: " );
long n2 = input.nextLong();

int gcd = 1;
for (int k = 1; k <= n1 && k <= n2; ++k) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
}

System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);
}

找出两个正整数的最大公约数(欧几里得算法)

public static int gcd(int m, int n) {
if (m % n == 0)
return n;
else
return gcd(n, m % n);
}

十六进制转十进制

/*
* 十进制转十六进制
**/
@Test
public void dec2Hex() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = "";

while (decimal != 0) {
int hexValue = decimal % 16;
char hexDigit = (hexValue <= 9 && hexValue >= 0) ? (char)(hexValue + '0') : (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
System.out.println("The hex number is " + hex);
}

十六进制转十进制

/*
* 十六进制转十进制
**/
@Test
public void hex2Dec2() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number: ");
String hex = input.nextLine();
System.out.println("The decimal value for hex number " + hex + " is " + hex2Decimal(hex.toUpperCase()));
}

public static int hex2Decimal(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); ++i) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexChar2Decimal(hexChar);
}

return decimalValue;
}

public static int hexChar2Decimal(char ch) {
return (ch >= 'A' && ch <= 'F') ? 10 + ch - 'A' : ch - '0';
}

判断回文串(字符串)

/*
* 判断回文串(字符串)
**/
@Test
public void palindromeString() {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = input.nextLine();
int low = 0;
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;
}
low++;
high--;
}

s += isPalindrome ? " is a palindrome" : " is not a palindrome";
System.out.println(s);
}

判断回文串(字符串 - 递归解法)

public class RecursivePalindrome {
public static boolean isPalindrome(String s) {
return isPalindrome(s, 0, s.length() - 1);
}

private static boolean isPalindrome(String s, int low, int high) {
if (high <= low)
return true;
else if (s.charAt(low) != s.charAt(high))
return false;
else
return isPalindrome(s, low + 1, high - 1);
}

public static void main(String[] args) {
System.out.println("Is moon a palindrome? " + isPalindrome("moon"));
System.out.println("Is noon a palindrome? " + isPalindrome("noon"));
System.out.println("Is a a palindrome? " + isPalindrome("a"));
System.out.println("Is aba a palindrome? " + isPalindrome("aba"));
System.out.println("Is ab a palindrome? " + isPalindrome("ab"));
}
}

判断回文数

/*
* 判断回文数
**/
@Test
public void palindromeInt() {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();

if (number < 0 || (number % 10 == 0 && number != 0))
System.out.println(false);

int reversedNumber = 0;
while (number > reversedNumber) {
reversedNumber = reversedNumber * 10 + number % 10;
number /= 10;
}

System.out.println(number == reversedNumber || number == reversedNumber / 10);
}

求 100 以内质数

/*
* 输出 100 以内的质数
* */
@Test
public void printNumber() {
label:for (int i = 2; i <= 100; ++i) {
for (int j = 2; j <= Math.sqrt(i); ++j) {
if (i % j == 0) {
continue label;
}
}
System.out.println(i);
}
}

打印环形矩阵

/*
* 打印环形矩阵
* Enter an integer: 4
* 01 02 03 04
* 12 13 14 05
* 11 16 15 06
* 10 09 08 07
* */
@Test
public void printCircularMatrix() {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = input.nextInt();
int[][] array = new int[n][n];

int count = 0;
int maxX = n - 1;
int maxY = n - 1;
int minX = 0;
int minY = 0;

while (minX <= maxX) {
for (int x = minX; x <= maxX; ++x)
array[minY][x] = ++count;
minY++;
for (int y = minY; y <= maxY; ++y)
array[y][maxX] = ++count;
maxX--;
for (int x = maxX; x >= minX; --x)
array[maxY][x] = ++count;
maxY--;
for (int y = maxY; y >= minY; --y)
array[y][minX] = ++count;
minX++;
}

for (int[] eArray : array) {
for (int e : eArray) {
String space = (e + "").length() == 1 ? "0" : "";
System.out.print(space + e + "\t");
}
System.out.println();
}
}

随机抽取四张扑克牌

/*
* 随机抽取 4 张扑克牌
**/
@Test
public void deckOfCards() {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

for (int i = 0; i < deck.length; ++i)
deck[i] = i;

for (int i = 0; i < deck.length; ++i) {
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}

for (int i = 0; i < 4; ++i) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + ": " + rank + " of" + suit);
}
}

构建一个随机元素数组列表

要求数组列表中各元素不重复

ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 9; ++i) {
int temp = (int)(Math.random() * 9) + 1;
if (arrayList.contains(temp)) {
i--;
continue;
}
arrayList.add(i, temp);
}

设计一个有理数类

public class Rational extends Number implements Comparable<Rational> {
private long numerator = 0;
private long denominator = 1;

public Rational() {
this(0, 1);
}

public Rational(long numerator, long denominator) {
long gcd = gcd(numerator, denominator);
this.numerator = ((denominator > 0) ? 1 : -1) * numerator / gcd;
this.denominator = Math.abs(denominator) / gcd;
}

private static long gcd(long n, long d) {
long n1 = Math.abs(n);
long n2 = Math.abs(d);
int gcd = 1;

for (int k = 1; k <= n1 && k <= n2; ++k) {
if (n1 % k == 0 && n2 % k == 0)
gcd = k;
}

return gcd;
}

public long getNumerator() {
return numerator;
}

public long getDenominator() {
return denominator;
}

public Rational add(Rational secondRational) {
long n = numerator * secondRational.getDenominator() + denominator * secondRational.getNumerator();
long d = denominator * secondRational.getDenominator();
return new Rational(n, d);
}

public Rational subtract(Rational secondRational) {
long n = numerator * secondRational.getDenominator() - denominator * secondRational.getNumerator();
long d = denominator * secondRational.getDenominator();
return new Rational(n, d);
}

public Rational multiply(Rational secondRational) {
long n = numerator * secondRational.getNumerator();
long d = denominator * secondRational.getDenominator();
return new Rational(n, d);
}

public Rational divide(Rational secondRational) {
long n = numerator * secondRational.getDenominator();
long d = denominator * secondRational.getNumerator();
return new Rational(n, d);
}

@Override
public String toString() {
if (denominator == 1)
return numerator + "";
else
return numerator + "/" + denominator;
}

@Override
public boolean equals(Object other) {
if (other instanceof Rational)
return (this.subtract((Rational) (other))).getNumerator() == 0;
else
throw new IllegalArgumentException();
}

@Override
public int intValue() {
return (int)doubleValue();
}

@Override
public float floatValue() {
return (float)doubleValue();
}

@Override
public double doubleValue() {
return numerator * 1.0 / denominator;
}

@Override
public long longValue() {
return (long)doubleValue();
}

@Override
public int compareTo(Rational o) {
if (this.subtract(o).getNumerator() > 0)
return 1;
else if (this.subtract(o).getNumerator() < 0)
return -1;
else
return 0;
}
}