利用 Groovy 生成输入数据:
def f = new File("input.txt")
int pos = 0
int floor = 0
int open = 0
int direction = 1
for(i=0; i<=80; i++){
pos = i
if(i>=0 && i<= 19) floor = 1
if(i>=20 && i<=39) floor = 2
if(i>=40 && i<=59) floor = 3
if(i>=60 && i<=79) floor = 4
if(i == 80) floor = 5
if(i==0 || i==20 || i==40 || i==60 ||i==80) open = 1
else open = 0
f.append(String.format("%d,%d,%d,%d",pos,floor,open,direction) + "\n")
}
主程序:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.TimerTask;
public class PLC {
public PLC(String filename) {
this.filename = filename;
}
private int lineno = 0;
private String filename = null;
public int getLineno() {
return lineno;
}
public void setLineno(int lineno) {
this.lineno = lineno;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public String readLine(int lineno) {
File file = new File(filename);
BufferedReader reader = null;
String result = "";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
if (line == lineno) {
result = tempString;
break;
}
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return result;
}
boolean validate(String line) {
boolean result = true;
String[] tokens = line.split(",");
int pos = Integer.valueOf(tokens[0]);
int floor = Integer.valueOf(tokens[1]);
int open = Integer.valueOf(tokens[2]);
int direction = Integer.valueOf(tokens[3]);
if (pos < 0 || pos > 80)
result = false;
if (pos >= 0 && pos <= 19 && floor != 1)
result = false;
if (pos >= 20 && pos <= 39 && floor != 2)
result = false;
if (pos >= 40 && pos <= 59 && floor != 3)
result = false;
if (pos >= 60 && pos <= 79 && floor != 4)
result = false;
if (pos == 80 && floor != 5)
result = false;
if ((pos == 0 || pos == 20 || pos == 40 || pos == 60 || pos == 80)
&& open != 1)
result = false;
if (pos != 0 && pos != 20 && pos != 40 && pos != 60 && pos != 80
&& open != 0)
result = false;
if (direction != 1)
result = false;
return result;
}
public static void main(String[] args) {
PLC plc = new PLC("input.txt");
java.util.Timer timer = new java.util.Timer(false);
TimerTask task = new TimerTask() {
public void run() {
plc.setLineno(plc.getLineno() + 1);
int lineno = plc.getLineno();
String line = plc.readLine(lineno);
if (null == line || "".equals(line)) {
System.exit(0);
}
boolean normal = plc.validate(line);
System.out.println(line + ": " + normal);
if (!normal) {
System.exit(1);
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
}
}