java - 从文本文件读取整数并存储到单独的变量中? (扫描器)

标签 java file parsing int java.util.scanner

我这里有一个由两部分组成的问题。因此,我正在为一个作业编写代码,尝试从文本文件中读取整数作为坐标。例如,我有一个标题为 test1 的文本文件,其内容如下:50 00 510 53 310 0。现在,这些整数应该代表坐标,这意味着 50 实际上转换为 (5,0)、(0,0)、 (5,10) 等等。

我正在尝试使用扫描仪进入该文本文件并选择该两位数整数中的第一个数字并将其存储为“x”值,然后选择第二个数字并将其存储为“y”值,然后冲洗剩余部分。

 int nSheep = 0;
 while (sc.hasNextLine()) {
     nSheep++;
     sc.nextLine();
 }

这是我当前的代码,用于确定文本文件中有多少只羊。它基本上只是读取有多少行,计算它们,并将它们存储在变量 nSheep 中。因此,在我的 test1 文件示例中,它将返回数字 6。

for (int i = 0; i < nSheep; i++) {
    while (sc.hasNextLine()) {
        int x = sc.nextInt();
        int y = sc.nextInt();
    }
    System.out.println(x);
} 

这是我尝试读取整数并将它们存储在变量 x 和 y 中。我无法判断这是否接近工作,因为 println 不打印任何内容。

终于...

xMin = xMax = sc.nextInt();
yMin = yMax = sc.nextInt();

//read the remaining coordinates
for (int i = 1; i <= nSheep - 1; i++) {
     while (sc.hasNextInt) {
        int x = sc.nextInt();
        int y = sc.nextInt();

        if (x < xMin)
            xMin = x;
        if (x > xMax)
            xMax = x;
        if (y < yMin)
            yMin = y;
        if (y > yMax)
            yMax = y;

        if (x < xMin)
           xMin = x;
        if (x > xMax)
           xMax = x;
        if (y < yMin)
           yMin = y;
        if (y > yMax)
           yMax = y;
    }
}
System.out.print("Fence Coordinates: {(" + xMin + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMax + "), ");
System.out.println("(" + xMin + "," + yMax + ") ");

如果我要求用户自己输入羊的数量和坐标,这就是成功的代码。与此唯一的区别是我不需要用户输入,我只需要扫描仪读取文本文件,确定坐标,然后将其打印出来。如果这个冗长的问题有道理,有人可以帮助我吗?

最佳答案

创建 File 实例来引用 Java 中的文本文件

File text = new File("C:/temp/test1.txt");

创建 Scanner 实例以读取 Java 中的文件

Scanner sc = new Scanner(text);

所以

File text = new File("C:/temp/test1.txt");
Scanner sc = new Scanner(text);

int xMin, xMax;
xMin = xMax = sc.nextInt();

int yMin, yMax
yMin = yMax = sc.nextInt();

while (sc.hasNextLine()) {
    int x = sc.nextInt();
    int y = sc.nextInt();

    if (x < xMin) { xMin = x; }
    if (y < yMin) { yMin = y; }
    if (x > xMax) { xMax = x; }
    if (y > yMax) { yMax = y; }
}

System.out.println("Fence Coordinates:"
System.out.print("{ (" + xMin + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMax + "), ");
System.out.print("(" + xMin + "," + yMax + ") } ");

关于java - 从文本文件读取整数并存储到单独的变量中? (扫描器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60145010/

相关文章:

c - scanf c 中的正则表达式?

java - Spring 批量插入中的提交大小

java - maven-jaxws-tools-plugin 错误 : ClassNotFoundException

c - fstat 获取文件大小为零

支持 UTF-8 的 C++ 解析库

python - 按行解析 HTML

java - Boolean.TRUE 而不是 true 是自动装箱优化吗?

java - 安卓默认屏幕方向

java - 在 Java 中反转文件(图像、音乐)会损坏文件

java - 如何读取大文本文件并在 Java 中使用它