我正在尝试实现会议安排算法。我想随机生成会议并将其存储在文件中。然后在另一个代码中读取此文件,创建将尝试安排这些会议的不同代理。
我的输入会议文件如下:
1 20 25 [1, 2, 3, 4, 5] [4, 5]
2 21 29 [1, 6, 7, 5, 33] [1, 5, 33]
从左到右,这些值指示会议 ID、开始时间、硬截止日期、与会者 ID 列表、基本与会者 ID 列表。
基本上它是整数和整数数组列表的组合(动态,大小不固定)。为了存储它,我使用了这段代码
File fleExample = new File("Meeting.txt")
PrintWriter M1 = new PrintWriter(fleExample);
M1.print(m.getMeetingID()+" "+m.getStartTime()+" "+m.getHardDeadLine()+" "+m.getAttendees()+" "+m,getEssentialAttendees());
M1.println();
我想读取这些值并将其设置为整数变量和整数数组列表。
FileInputStream fstream = new FileInputStream("Meeting.txt");
DataInputStream inp = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(inp));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(" ");
for (int i = 0; i < MeetingCount; i++) {
Meeting meet = new Meeting();
meet.setMeetingID(Integer.valueOf(tokens[0]));
meet.setStartTime(Integer.valueOf(tokens[1]));
meet.setHardDeadLine(Integer.valueOf(tokens[2]));
}
}
我能够将值设置为整数,但找不到对 arraylist 执行相同操作的方法。我想将字符串存储到数组列表中。在这个方向上的任何帮助都会很大。
我不确定您的实现是做什么的(以及Meeting
对象是关于什么的),但是如果您只想将它们分配给 int 或列表变量,请尝试使用扫描仪并逐个读取它们:
String str = "1 20 25 [1 2 3] [4 5]";
Scanner scan = new Scanner(str);
int intVariable = 0;
ArrayList<Integer> listVariable = null; //null marks no active list
while (scan.hasNext()) { //try/catch here is highly recommeneded!
//read next input (separated by whitespace)
String next = scan.next();
if (next.startsWith("[")) {
//init new list and store first value into it
listVariable = new ArrayList<Integer>();
listVariable.add(Integer.parseInt(next.substring(1)));
} else if (next.endsWith("]")) {
//add the last item to the list
listVariable.add(Integer.parseInt(next.substring(0, next.length()-1)));
System.out.println(Arrays.toString(listVariable.toArray()));
//reset the list to null
listVariable = null;
} else {
//if inside a list, add it to list, otherwise it is simply an integer
if (listVariable != null) {
listVariable.add(Integer.parseInt(next));
} else {
intVariable = Integer.parseInt(next);
System.out.println(intVariable);
}
}
}
在这里,我只是打印了输出,但您当然可以将其投影到您的任何需求,或者有一个整数值列表和一个整数列表值列表。
另请注意,在此示例中,我只获取了文件的一行,但您可以直接向扫描仪提供您的文件(无需自己逐行读取)。
希望这有帮助。
String fileinput="2 21 29 [6 7] [71 45 33]";
Pattern p=Pattern.compile("[0-9]+");
Matcher m=p.matcher(fileinput);
while (m.find()) {
int i=Integer.parseInt(fileinput.substring(m.start(), m.end()));
System.out.println(i);
}
上述问题通过使用正则表达式来解决,其中它连续搜索一个或多个整数,并在找不到更多整数时中断。此过程将重复到字符串末尾。m.find 将返回已识别模式的开始和结束位置。使用开始值和结束值,我们从主字符串中提取子字符串,然后解析为 Integer。