Java常见练手程序《“书写”百遍,其义自见》
发布人:shili8
发布时间:2025-02-27 12:18
阅读次数:0
**《"书写"百遍,其义自见》**
作为一名Java开发者,为了提高编程技能和理解力,我们需要不断地实践和挑战自己。以下是一些常见的练手程序,可以帮助你加深对Java语言的理解。
###1. 单词翻译器**需求:**
* 用户输入一个单词* 程序输出该单词的中文翻译**实现:**
javaimport java.util.Scanner; public class WordTranslator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入要翻译的单词:"); String word = scanner.nextLine(); // 使用API或数据库进行翻译 String translation = translateWord(word); System.out.println("翻译结果:" + translation); } private static String translateWord(String word) { // 这里可以使用API或数据库进行实际的翻译工作 return "暂未实现"; } }
###2. 质数检测器**需求:**
* 用户输入一个数字* 程序输出该数字是否为质数**实现:**
javaimport java.util.Scanner; public class PrimeDetector { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入要检测的数字:"); int number = scanner.nextInt(); // 检测是否为质数 boolean isPrime = isPrime(number); System.out.println(isPrime ? "是质数" : "不是质数"); } private static boolean isPrime(int number) { if (number <=1) return false; for (int i =2; i * i <= number; i++) { if (number % i ==0) return false; } return true; } }
###3. 数组排序器**需求:**
* 用户输入一个数组* 程序输出该数组的升序或降序排列**实现:**
javaimport java.util.Arrays; public class ArraySorter { public static void main(String[] args) { int[] array = {4,2,9,6,5}; // 升序排序 Arrays.sort(array); System.out.println("升序排列:" + Arrays.toString(array)); // 降序排序 Arrays.sort(array); for (int i = array.length -1; i >=0; i--) { System.out.print(array[i] + " "); } } }
###4. 链表操作器**需求:**
* 用户输入一个链表* 程序输出该链表的长度、最大值和最小值**实现:**
javapublic class LinkedListOperator { public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); // 获取链表长度 int length = getLength(head); System.out.println("链表长度:" + length); // 获取最大值和最小值 int max = getMax(head); int min = getMin(head); System.out.println("最大值:" + max); System.out.println("最小值:" + min); } private static int getLength(Node head) { if (head == null) return0; return1 + getLength(head.next); } private static int getMax(Node head) { if (head == null) return Integer.MIN_VALUE; return Math.max(head.value, getMax(head.next)); } private static int getMin(Node head) { if (head == null) return Integer.MAX_VALUE; return Math.min(head.value, getMin(head.next)); } }
###5. 栈和队列操作器**需求:**
* 用户输入一个栈或队列* 程序输出该栈或队列的长度、最大值和最小值**实现:**
javapublic class StackAndQueueOperator { public static void main(String[] args) { // 栈操作 Stack stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); System.out.println("栈长度:" + stack.size()); System.out.println("最大值:" + stack.max()); System.out.println("最小值:" + stack.min()); // 队列操作 Queue queue = new Queue(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); System.out.println("队列长度:" + queue.size()); System.out.println("最大值:" + queue.max()); System.out.println("最小值:" + queue.min()); } }
以上这些练手程序可以帮助你加深对Java语言的理解,并且可以作为你的编程技能和理解力的提高。