【问题标题】:How do you print out the last position or occurrence of a number within a file without an array?如何在没有数组的情况下打印出文件中数字的最后位置或最后一次出现?
【发布时间】:2022-11-29 10:27:26
【问题描述】:

我试图从名为 numbers.text 的文件中仅打印出数字的最后一个位置 #。 数字.文字:

10
23
43
5
12
23
9
8
10
1
16
9

基本上,我试图打印出一条语句(以 10 为例)“10 最后出现在位置 9”。

import java.io.File;
import java.util.*;

public class SortOf3 {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        Scanner datafile = new Scanner(new File("numbers.text"));

        boolean duplicate = true;
        int count = 0;
        int duplicate = 0
        while (datafile.hasNextInt()) {
            if (duplicate) {
                System.out.print("Enter a number: ");
                lastNumber = scanner.nextInt();
                count++;
                duplicate = false;
            } else {
                System.out.print("Enter a number: ");
                lastNumber = scanner.nextInt();
                count++;
            }
  

                if (lastNumber == datafile.nextInt())
                    System.out.println(lastNumber + " last appears in the file at position " + count);
                else
                    System.out.println(lastNumber + " does not appear in the file");
                }
            }
        }

我尝试使用 boolean duplicate,希望在 lastNumber 第一次出现时忽略计数器,但它似乎没有做任何事情。如果这里没有办法使布尔值工作,那么打印出文件中数字最后位置的另一种方法是什么?

【问题讨论】:

  • 你的代码有问题吗?

标签: java


【解决方案1】:

在声明未找到之前,您需要彻底检查 number。另外,我会先将这些行读入List,然后您可以通过List向后搜索以找到值的最后一次出现(因为我们向后扫描,那将是从右手开始的第一个边)。就像是,

Scanner scanner = new Scanner(System.in);
try {
    List<String> lines = Files.readAllLines(new File("numbers.text").toPath());
    System.out.print("Enter a number (-1 to quit): ");
    int lastNumber;
    while ((lastNumber = scanner.nextInt()) != -1) {
        boolean found = false;
        for (int j = lines.size(); j >= 0 && !found; j--) {
            if (Integer.parseInt(lines.get(j)) == lastNumber) {
                System.out.println(
                        lastNumber
                        + " last appears in the file at position "
                        + j);
                found = true;
            }
        }
        if (!found) {
            System.out.println(lastNumber + " does not appear in the file");
        }
        System.out.print("Enter a number (-1 to quit): ");
    }
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

  • 你的代码抛出IndexOutOfBoundsException
【解决方案2】:

您可以尝试使用 HashMap

Map<String, Integer> map = new HashMap<>();

在你的时候,如果你找到了你正在搜索的值,你可以把它放在你的 HashMap 中

  map.put(value, position);

您可以通过计数器获得位置,然后当 while 结束时您只需获得位置

map.get(value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多