下面是一些简单的 Java 编程实例,包括相加数字、计算单词数、字符串反转、元素求和、矩形面积计算和奇偶判断:
public class AddNumbers { public static void main(String[] args) { int num1 = 5, num2 = 10, sum; sum = num1 + num2; System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum); } }
public class WordCount { public static void main(String[] args) { String sentence = "This is a sample sentence"; String[] words = sentence.split("\\s+"); int wordCount = words.length; System.out.println("Word count: " + wordCount); } }
public class StringReverse { public static void main(String[] args) { String str = "Hello World"; StringBuilder reversed = new StringBuilder(); reversed.append(str); reversed = reversed.reverse(); System.out.println("Reversed string: " + reversed); } }
public class ArraySum { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int num : numbers) { sum += num; } System.out.println("Sum of array elements: " + sum); } }
public class RectangleArea { public static void main(String[] args) { int length = 5; int width = 10; int area = length * width; System.out.println("Area of rectangle: " + area); } }
public class OddEven { public static void main(String[] args) { int num = 5; if (num % 2 == 0) { System.out.println(num + " is even."); } else { System.out.println(num + " is odd."); } } }
这些例子展示了 Java 编程中一些常见的操作,可以帮助你开始学习和练习 Java 编程。
原文链接:codingdict.net