本周我自学了Java的输入与输出
包括了:
-
使用Scanner类进行输入
导入Scanner类:import java.util.Scanner;
创建Scanner对象:Scanner scanner = new Scanner(System.in);
读取不同类型的数据:
读取字符串:String inputString = scanner.nextLine();
读取整数:int inputInt = scanner.nextInt();
读取浮点数:double inputDouble = scanner.nextDouble();
示例代码:
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String inputString = scanner.nextLine();
System.out.println("您输入的字符串是:" + inputString);
System.out.println("请输入一个整数:");
int inputInt = scanner.nextInt();
System.out.println("您输入的整数是:" + inputInt);
scanner.close();
}
} -
使用BufferedReader类进行输入
导入BufferedReader类:import java.io.BufferedReader;
导入InputStreamReader类:import java.io.InputStreamReader;
创建BufferedReader对象:BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
读取字符串:String inputString = reader.readLine();
示例代码:
java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个字符串:");
String inputString = reader.readLine();
System.out.println("您输入的字符串是:" + inputString);
reader.close();
}
} -
使用System.out.println()和System.out.print()方法
输出字符串:System.out.println("Hello, world!");
输出变量值:int num = 10; System.out.println("数值为:" + num);
4.使用PrintWriter类进行输出
导入PrintWriter类:import java.io.PrintWriter;
创建PrintWriter对象:PrintWriter writer = new PrintWriter(System.out);
输出内容:writer.println("Hello, world!");
刷新并关闭输出流:writer.flush(); writer.close();
示例代码:
java
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) {
PrintWriter writer = new PrintWriter(System.out);
writer.println("Hello, world!");
writer.flush();
writer.close();
}
}
并完成了我的java语言的第一个程序“输出Hello world”
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}