[英]Why does processing goes slower on implementing try catch block in java?
我一直在研究一個問題,
它只需從控制台逐行讀取並找到包含模式的部分,然后將其替換為實際數字
資源: spoj
首先,我嘗試使用查找文本的模式,並根據需要通過加或減將其替換為實際數字
我的密碼
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
Pattern pattern = Pattern.compile("machula");
Matcher matcher = pattern.matcher(numArray[1]);
if(matcher.find()) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
else {
matcher = pattern.matcher(numArray2[0]);
if(matcher.find()) {
System.out.println((Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[1])) + " + " + numArray2[1] + " = " + numArray[1]);
}
else {
System.out.println(numArray2[0] + " + " + (Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[0])) + " = " + numArray[1]);
}
}
t--;
}
}
}
我在ideone上用120個測試用例實現了它
成功時間:0.14內存:320832信號:0
在那之后,為了進行測試,我完全消除了模式和匹配器,而改用try catch
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
int a = 0, b = 0, c = 0;
try {
c = Integer.parseInt(numArray[1]);
try {
a = Integer.parseInt(numArray2[0]);
System.out.println(a+" + "+(c - a)+" = "+c);
}
catch(NumberFormatException nfe) {
b = Integer.parseInt(numArray2[1]);
System.out.println((c - b)+" + "+b+" = "+c);
}
}
catch(NumberFormatException nfe) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
t--;
}
}
}
我用相同的輸入結果
成功時間:0.15內存:320832信號:0
我無法弄清楚,為什么即使刪除了find方法作業,下一次實現的時間也會增加。
是因為try-catch嗎?如果是,為什么呢?
除了嵌套try catch,我們可以將內部try catch帶到外部catch塊之后。 我沒有確切的理由認為try try catch的嵌套不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.