欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
一、Java之ACM注意点
1. 类名称必须采用public class Main方式命名
2. 在有些OJ系统上,即便是输出的末尾多了一个” “,程序可能会输出错误,所以在我看来好多OJ系统做的是非常之垃圾
3. 有些OJ上的题目会直接将OI上的题目拷贝过来,所以即便是题目中有输入和输出文件,可能也不需要,因为在OJ系统中一般是采用标准输入输出,不需要文件
4. 在有多行数据输入的情况下,一般这样处理,
static Scanner in = new Scanner(System.in);
while(in.hasNextInt())
或者是
while(in.hasNext())
5. 有关System.nanoTime()函数的使用,该函数用来返回最准确的可用系统计时器的当前值,以毫微秒为单位。
long startTime = System.nanoTime();
// … the code being measured …
long estimatedTime = System.nanoTime() – startTime;
二、Java之输入输出处理
由于ACM竞赛题目的输入数据和输出数据一般有多组(不定),并且格式多种多样,所以,如何处理题目的输入输出是对大家的一项最基本的要求。这也是困扰初学者的一大问题。
1. 输入:
格式1:Scanner sc = new Scanner (new BufferedInputStream(System.in));
格式2:Scanner sc = new Scanner (System.in);
在读入数据量大的情况下,格式1的速度会快些。
读一个整数: int n = sc.nextInt(); 相当于 scanf(”%d”, &n); 或 cin 》 n;
读一个字符串:String s = sc.next(); 相当于 scanf(”%s”, s); 或 cin 》 s;
读一个浮点数:double t = sc.nextDouble(); 相当于 scanf(”%lf”, &t); 或 cin 》 t;
读一整行: String s = sc.nextLine(); 相当于 gets(s); 或 cin.getline(…);
判断是否有下一个输入可以用sc.hasNext()或sc.hasNextInt()或sc.hasNextDouble()或sc.hasNextLine()
例1:读入整数
Input 输入数据有多组,每组占一行,由一个整数组成。
Sample Input
56
67
100
123
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(sc.hasNext()){ //判断是否结束
int score = sc.nextInt(); //读入整数
…
}
}
}
例2:读入实数
输入数据有多组,每组占2行,第一行为一个整数N,指示第二行包含N个实数。
Sample Input
4
56.9 67.7 90.5 12.8
5
56.9 67.7 90.5 12.8
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
for(int i=0;i
double a = sc.nextDouble();
……
}
}
}
}
例3:读入字符串【杭电2017 字符串统计】
输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。
Sample Input
2
asdfasdf123123asdfasdf
asdf111111111asdfasdfasdf
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i
String str = sc.next();
……
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for(int i=0;i
String str = sc.nextLine();
……
}
}
}
[1][2][3]
走过一个又一个陌生的城市,去感受旖旎的自然风光,