繁体   English   中英

如何在文本文件中读取行列表的位置

[英]How do I read a position of a list of lines in text file

我正在建立一个货运管理系统。 我想列出用户输入源端口和目标端口后在源和目标之间可用的中间端口。 但是我不知道该怎么做。 我将端口名称和每个端口的距离保存在文本文件中,其中每个端口一行。 location变量用于计算源和目标之间的距离。 我想使用position变量在源和目标之间定位端口。

新闻; 10;

哈里敦; 25;

真实; 33;

东港; 47;

雅典; 56;

纳斯基; 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语句。

快速的东西。

    boolean isPrint = false;
    while(file.hasNextLine()){
        String line = file.nextLine();
        String[] split = line.split(";");
        if(split[0].equals(destination)){
           isPrint = false;
        }
        if (isPrint) { System.out.println(split[1]);}
        if(split[0].equals(source)){
             print = true;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM