【问题标题】:How do I read a position of a list of lines in text file如何读取文本文件中行列表的位置
【发布时间】:2017-01-24 15:47:23
【问题描述】:

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

新闻;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);
    }

【问题讨论】:

  • 请将源代码作为文本粘贴到您的问题中,而不是图像。还有什么不适用于您当前的代码?
  • 所有端口都在同一条几何线上吗?
  • 不,它们在不同的行中。

标签: java arrays file text


【解决方案1】:

如果我正确理解您的问题,您希望在源和目标之间显示端口。例如,如果用户选择“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 语句。

【讨论】:

    【解决方案2】:

    类似的东西。

        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;
            }
        }
    

    【讨论】:

    • 对不起,我的解释很糟糕,但我希望在用户输入源和目标后显示中间端口的名称。
    • 相应地改变了它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2013-12-18
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多