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程序的基本单元。通过编写和调用方法,可以实现程序的复杂逻辑和模块化设计。