输入输出练习

byjiangjb Lv2

记录一下常见的笔试输入输出的几种情况及代码实现

第一行输入一个整数n表示行数,接下来的n行都输入一个整数

1
2
3
4
5
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
}

也可以将n个整数存在数组当中

1
2
3
4
5
6
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}

第一行输入一个整数n表示行数,接下来的n行分别输入多个整数,以空格分开

1
2
3
4
5
6
7
8
9
10
11
12
13
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine(); // 消耗掉输入行末的换行符,否则按下回车键后程序报错
for (int i = 0; i < n; i++) {
String line = scanner.nextLine();
String[] str = line.split(" "); // 使用空格分割符串
for (int j = 0; j < str.length; j++) {
String s = str[j];
int num = Integer.parseInt(s);
System.out.print(num + " ");
}
System.out.println();
}

第一行输入一个整数n表示行数,接下来的n行输入不定长的字符串

1
2
3
4
5
6
7
8
Scanner scanner = new Scanner(System.in);
System.out.print("请输入行数n:");
int n = scanner.nextInt();
scanner.nextLine();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
str[i] = scanner.nextLine();
}
  • Title: 输入输出练习
  • Author: byjiangjb
  • Created at : 2023-08-19 20:08:57
  • Updated at : 2023-09-21 20:41:39
  • Link: https://redefine.ohevan.com/2023/08/19/输入输出练习/
  • License: This work is licensed under CC BY-NC-SA 4.0.