我正在构建一个 cargo 管理系统。我想在用户输入源端口和目标端口后列出源和目标之间可用的中间端口。但我不知道该怎么做。我将端口名称和每个端口的距离保存在文本文件中,每个端口一行。位置变量用于计算源和目的地之间的距离。我想使用位置变量来定位源和目标之间的端口。
Newes;10;
Harrytown;25;
Truy;33;
East Port;47;
Athens;56;
Nasky;71;
private int location, location1, position, position1;
private String source, destination;
public void choosePort(){
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please enter the source.");
source = sc.nextLine();
System.out.println("Please enter the destination.");
destination = sc.nextLine();
try{
File f = new File("Port.txt");
Scanner file = new Scanner(f);
while(file.hasNextLine()){
String line = file.nextLine();
String[] split = line.split(";");
if(split[0].equals(source)){
location = Integer.parseInt(split[1]);
position = i;
}
else if(split[0].equals(destination)){
location1 = Integer.parseInt(split[1]);
position1 = i;
}
i++;
}
file.close();
}
catch(IOException e){
System.out.println(e);
}
最佳答案
如果我正确理解您的问题,您希望在源和目标之间显示端口。例如,如果用户选择“Newes”作为起点,选择“Trury”作为目的地,您希望将“Harrytown”显示为中间点。有多种方法可以做到这一点。我认为最简单的方法是使用第二个扫描仪逐字扫描、分隔符和 while 循环内的打印语句。
while(file.hasNextLine())
{
String line = file.nextLine();
Scanner sff = new Scanner(line);
sff.useDelimiter(";"); // scanner will see ';' and skip over it
String temp1 = sff.next;
if ( source.equals(temp1))
{
System.out.println(file.nextLine());
}
之后,只需完成代码即可。编写另一个 file.nextLine()
来查看它是否与目标匹配,如果不匹配,则打印出该行。当 sff
与目标匹配时,打印出最后一行,然后插入 break
语句。
关于java - 如何读取文本文件中行列表的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41832413/