gpt4 book ai didi

java - 在没有比较器的情况下对java中的路径名数组列表进行排序

转载 作者:行者123 更新时间:2023-12-01 18:06:38 25 4
gpt4 key购买 nike

我的用户输入是

\home\me\cs1

\usr\share

\var\log

\usr\local\jdk1.6.0\jre\lib

我需要对这些路径名进行排序,以便输出按正确的字典顺序排列。然而,它们首先按长度排序,即每个字符串中斜杠的数量。路径名存储在字符串数组列表中。我尝试在不使用集合、比较器或数组的情况下执行此操作。使用 ArrayList 可以实现这一点吗?

输出应该是:

\usr\share

\var\log

\home\me\cs1

\usr\local\jdk1.6.0\jre\lib

这是我到目前为止的代码:

import java.util.ArrayList;
import java.util.Scanner;
public class FileName
{
private ArrayList<String> pathNames;

public FileName()
{
pathNames = new ArrayList<String>();
}

public void printPaths()
{
for(int i = 0; i < pathNames.size(); i++)
{
System.out.println(pathNames.get(i));
}
}
public int pathLength(String path)
{
int count = 0;
String slash = "\\";
for(int i = 0; i < path.length(); i++)
{
if(path.substring(i,i + 1).equals(slash))
{
count++;
}
}
return count;
}

public void sort()
{
pathNames = mergeSort(pathNames);
}
public ArrayList<String> mergeSort(ArrayList<String> paths)
{
if(paths.size() == 1)
{
return paths;
}
else
{
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
int middle = paths.size() / 2;
for(int i = 0; i < middle; i++)
{
left.add(paths.get(i));
}

for(int i = middle; i < paths.size(); i++)
{
right.add(paths.get(i));
}

right = mergeSort(left);
left = mergeSort(left);

merge(left, right, paths);
}
return paths;
}

public void merge(ArrayList<String> left, ArrayList<String> right, ArrayList<String> paths)
{
int leftNum = 0;
int rightNum = 0;
int pathsNum = 0;
while (leftNum < left.size() && rightNum < right.size())
{
if ((left.get(leftNum).compareTo(right.get(rightNum)))<0)
{
paths.set(pathsNum, left.get(leftNum));
leftNum++;
}
else
{
paths.set(pathsNum, right.get(rightNum));
rightNum++;
}
pathsNum++;
}

ArrayList<String>rest;
int restNum;
if (leftNum >= left.size())
{
rest = right;
restNum = rightNum;
}
else
{
rest = left;
restNum = leftNum;
}

for (int i = restNum; i < rest.size(); i++)
{
paths.set(pathsNum, rest.get(i));
pathsNum++;
}

}
public void readInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a list of path names.(press enter after each path name, and type \"stop\" once you are finished.");
String termination = "stop";
String in = input.nextLine();
boolean reading = true;
while(reading)
{
pathNames.add(in);
if(in.equals(termination))
{
reading = false;
return;
}
in = input.nextLine();
}
}
}

这是我的主要方法。

public class FileNamePrgm 
{
public static void main(String [] args)
{
FileName paths = new FileName();
paths.readInput();
paths.sort();
}
}

最佳答案

您有一个拼写错误:

right = mergeSort(left);

应该是

right = mergeSort(right);

您还需要在 while 循环内再次添加 in = input.nextLine(); 。目前,您仅从输入中读取一行并一遍又一遍地检查它。

关于java - 在没有比较器的情况下对java中的路径名数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35934764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com