导包
import java.lang.*;
import java.util.*;
关键在于:Scanner
Scanner scanner = new Scanner(System.in);
循环等待依次读取每一个数值:
while (scanner.hasNext()) {
int n = scanner.nextInt();
}
换行读取:sc.hasNextLine(),读取一行输入为字符串,一般通过String[] items = line.split(" ");分割得到数组和集合再对单项做处理
读取数值有:
nextInt输入示例:
输入描述
- 每行的第一个数N,表示本行后面有N个数。
- 如果N=0时,表示输入结束,且这一行不要计算。
4 1 2 3 4
5 1 2 3 4 5
0
代码模版:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n == 0) {
break;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += scanner.nextInt();
}
System.out.println(sum);
}
输入示例:
输入描述
输入的第一行为一个整数N,接下来N行每行先输入一个整数M,然后在同一行内输入M个整数。
输出描述
对于每组输入,输出M个数的和,每组输出之间输出一个空行。
输入示例
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
输出示例
10
15
6
代码模版:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
int N = sc.nextInt();
while(N-- > 0){
int M = sc.nextInt();
int sum = 0;
while(M-- > 0){
sum += sc.nextInt();
}
System.out.println(sum);
if(N > 0) System.out.println();
}
}
}
}
有映射关系,先定义HashMap等静态变量并在Static静态代码块中完成赋初值
处理集合,一般sc.nextLine();读取一行输入为字符串,再通过String[] items = line.split(" ");分割
输入示例:
每门课的成绩分为A、B、C、D、F五个等级,为了计算平均绩点,规定A、B、C、D、F分别代表4分、3分、2分、1分、0分。
输入描述
有多组测试样例。每组输入数据占一行,由一个或多个大写字母组成,字母之间由空格分隔。
输出描述
每组输出结果占一行。如果输入的大写字母都在集合{A,B,C,D,F}中,则输出对应的平均绩点,结果保留两位小数。否则,输出“Unknown”。
输入示例
A B C D F
B F F C C A
D C E F
输出示例
2.00
1.83
Unknown
代码模版:
public class Main{
public static Map<String,Integer> map = new HashMap<>();
static{
map.put("A",4);
map.put("B",3);
map.put("C",2);
map.put("D",1);
map.put("F",0);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] items = line.split(" ");
double sum = 0.0;
int count = 0;
boolean flag = false;
for(String item:items){
if(map.get(item) != null){
sum += map.get(item);
count++;
}else{
flag = true;
}
}
if (flag) {
System.out.println("Unknown");
} else {
System.out.printf("%.2f\n", sum / count);
}
}
}
}
ArrayList<Integer> list = new ArrayList<>();
Integer sum = 0;
for (int i = 0; i < size; i++) {
int num = scanner.nextInt();
sum += num;
list.add(num);
}
list.get(i)
换行输出ln:
System.out.println();
格式化:
System.out.printf("%.2f\n", sum / count);