java中的输入输出语句
时间: 2024-06-11 09:04:44 浏览: 18
Java中的输出语句有四种:
1. System.out.println(1111); - 换行打印
2. System.out.print(1111); - 不换行打印
3. System.out.write(2222); - 字节输出
4. System.out.printf("% 8.3f\n", 3.14); - 按格式输出
System.out.println()是最常用的输出语句,它会将括号内的内容转换成字符串输出到控制台,并且在末尾换行。如果输出的是基本数据类型,会自动转换为字符串。如果输出的是对象,会自动调用对象的toString()方法并将返回值输出。
System.out.print()与System.out.println()类似,区别在于前者输出后不换行。
System.out.printf()方法继承了C语言的输出方式,通过格式化文本和参数列表输出。
Java中的输入语句有以下几种方式:
1. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine(); - 使用BufferedReader的readLine()方法读取一行输入
2. Scanner类的常用方法系列:
- nextInt(): 输入整数
- nextLine(): 输入字符串
- nextDouble(): 输入双精度数
- next(): 输入字符串(以空格作为分隔符)
以下是一个示例代码:
import java.util.*;
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入姓名:");
String name = scanner.nextLine();
System.out.print("请输入年龄:");
int age = scanner.nextInt();
System.out.println("姓名:" + name + " 年龄:" + age);
scanner.close(); // 关闭Scanner对象
}
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)