📅  最后修改于: 2023-12-03 14:53:36.425000             🧑  作者: Mango
Java是一种跨平台的高级编程语言,适用于开发Web应用程序、移动应用程序、桌面应用程序和嵌入式系统。
以下是一些Java实例,你可以使用它们来学习和练习Java编程。
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
此程序会输出 Hello, World!
到控制台。
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = input.nextDouble();
System.out.print("Enter second number: ");
double second = input.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = input.next().charAt(0);
double result = 0.0;
switch(operator) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println(first + " " + operator + " " + second + " = " + result);
input.close();
}
}
此程序是一个简单的命令行计算器,可以进行基本的算术运算。
注意:这个程序中有一些特殊的字符,例如 Scanner
和 switch-case
语句,这些在后续学习Java时会涉及到。
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100) + 1;
Scanner input = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and 100. Can you guess what it is?");
int guess = 0;
int numGuesses = 0;
while (guess != number) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
numGuesses++;
if (guess < number) {
System.out.println("Too low. Try again.");
} else if (guess > number) {
System.out.println("Too high. Try again.");
} else {
System.out.println("Congratulations! You guessed the number in " + numGuesses + " guesses!");
}
}
input.close();
}
}
此程序是一个猜数字游戏,会生成一个1到100之间的随机数,并等待用户猜测。
import java.util.ArrayList;
import java.util.Scanner;
public class TodoList {
public static void main(String[] args) {
ArrayList<String> todoList = new ArrayList<>();
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a task to add to the list (or 'quit' to exit): ");
String task = input.nextLine();
if (task.equals("quit")) {
break;
}
todoList.add(task);
System.out.println("Task added to the list.");
}
System.out.println("TODO List:");
for (String task : todoList) {
System.out.println("- " + task);
}
input.close();
}
}
此程序是一个简单的TODO清单,可以添加任务并显示任务列表。
这些Java实例很适合初学者学习和练习Java编程。 这些实例涵盖了Java编程的许多方面,包括语法、基本编程概念和数据结构等。