介紹
大家好,我是 Java 編程的新手。原諒我,如果我可能重復問了
題。曾試圖在堆疊上四處尋找類似的答案,但不能。
已經被困在這幾天了。
我想讀取文本檔案的最后兩位數字并使用正則運算式進行驗證。如果大于 70
系統應該列印“他們正在超速行駛。”;
這將是文本檔案的草稿。
AB12345-60
AB22345-60
AB32345-80
示例 Java 代碼:
import java.io.*;
class Main {
private final int LinesToRead = 3;
private final String REGEX = ".{2}\d{5}[-]\d{2}";
public void testFile(String fileName) {
int lineCounter = 1;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while ((line != null) && (lineCounter <= LinesToRead)) {
if (line.matches(REGEX)) {
System.out.println("They are not speeding");
}
else {
System.out.println("They are speeding");
}
line = br.readLine();
lineCounter ;
}
} catch (Exception ex) {
System.out.println("Exception occurred: " ex.toString());
}
}
public static void main(String[] args) {
Main vtf = new Main();
vtf.testFile("Data.txt");
} }
uj5u.com熱心網友回復:
我建議只做一個字串拆分來隔離最終的速度數字,然后通過不等式來檢查它:
while ((line != null) && (lineCounter <= LinesToRead)) {
int speed = Integer.parseInt(line.split("-")[1]);
if (speed > 70) {
System.out.println("They are speeding");
}
else {
System.out.println("They are not speeding");
}
line = br.readLine();
lineCounter ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340850.html
