在我的代码中,该方法能够读取 .txt 文件并将整数放入数组的一侧,将双精度数放入另一侧。但是,在输出中存在重复项,我试图将它们按升序排列,没有重复项。
public static void readFile(String file) throws FileNotFoundException
{
Scanner s1 = new Scanner(new File(file));
String[][] container = new String[2][2];
int intIndex = 0;
int doubleIndex = 0;
while(s1.hasNextLine())
{
String line = s1.nextLine();
System.out.println(line);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String[] splitLine = line.split(" ");
for (String text : splitLine) {
if (text.matches("\\d*"))
{
System.out.println(text + " is int");
if (container[0].length == intIndex)
{
container[0] = Arrays.copyOf(container[0], intIndex + 2); //add two more slot to int array
container[1] = Arrays.copyOf(container[1], intIndex + 2); //add two more slot to double array
}
container[0][intIndex] = (text); //add to container
intIndex++; //adjust the index
} else if (text.matches("\\d*.\\d*"))
{
System.out.println(text + " is double");
if (container[1].length == doubleIndex)
{
container[0] = Arrays.copyOf(container[0], doubleIndex + 2); //add two more slot to int array
container[1] = Arrays.copyOf(container[1], doubleIndex + 2); //add two more slot to double array
}
container[1][doubleIndex] = (text); //add to container
doubleIndex++; //adjust the index
} else
{
System.out.println(text + " is not int nor double");
}
}
}
.txt 文件将所有内容包含在一行中,“10 5 Five 10 1.5 2 2.0 20”
我期望输出为: [2, 10, 20] [1.5, 2.0]
然而,我得到的实际输出是: [10, 10, 2, 20] [1.5, 2.0, null, null]
达令说
相关分类