Java方法是一段具有特定功能的代碼塊,它可以接收輸入參數,執行特定操作,并返回一個結果。Java方法的主要功能包括:
public int add(int a, int b) {
return a + b;
}
public String reverseString(String input) {
return new StringBuilder(input).reverse().toString();
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
public int calculateArea(int length, int width) {
return length * width;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age is " + age);
}
}
import java.io.File;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String[] args) {
File file = new File("example.txt");
try (FileReader fr = new FileReader(file)) {
int content;
while ((content = fr.read()) != -1) {
System.out.print((char) content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
總之,Java方法可以實現各種功能,它們是構成Java程序的基本單元。通過編寫和調用方法,可以實現程序的復雜邏輯和模塊化設計。