我想更快地制作以下代码,而无需更改标准控制台的读/写。第一行包含输入数,后续行包含一组Integer
s。
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
try {
java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int a = Integer.parseInt(r.readLine());
for (int i = 0; i < a; i++) {
StringTokenizer st = new StringTokenizer(r.readLine());
while (st.hasMoreTokens()) {
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}
答案 0 :(得分:0)
如果您将first
和second
定义为原始int
而不是java.lang.Integer
包装类,那么您正在执行大量冗余自动装箱和发件箱,可以保存这些内容。但是,我怀疑,对于任何合理的输入大小,你甚至都会注意到差异。
答案 1 :(得分:0)
以下是一些建议,我不确定这些建议会有多大帮助。
1)这个,
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
可以更改为
System.out.println(first < second
? "<"
: first > second
? ">"
: "="
);
2)由于你使用的是throws子句而你的try-catch
什么都不做,你可以删除它。
3)在这里,
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
您第二次没有检查hasMoreTokens()
。
答案 2 :(得分:0)
您可以考虑使用下面的BufferedReader
构造函数:
public BufferedReader(Reader in, int sz)
为sz
参数提供合理的高值,可以避免过于频繁地重新填充缓冲区。
作为旁注,虽然readLine()
在达到流的末尾时重新调整null
,但最好在调用new StringTokenizer(r.readLine())
和Integer.parseInt(r.readLine())
之前检查其返回值。
编辑后的课程如下:
public class Main {
public static void main(String[] args) {
BufferedReader r;
String line;
StringTokenizer st;
int a, first, second;
r = new BufferedReader(new InputStreamReader(System.in), 4096);
try {
line = r.readLine();
if (line != null) {
a = Integer.parseInt(line);
for (int i = 0; i < a; ++i) {
line = r.readLine();
if (line == null)
break;
st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
first = Integer.parseInt(st.nextToken());
second = Integer.parseInt(st.nextToken());
if (first < second)
System.out.println("<");
else if (first > second)
System.out.println(">");
else
System.out.println("=");
}
}
}
r.close();
} catch (Exception e) {
System.err.print(e.getMessage());
}
}
}