繁体   English   中英

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

[英]Reading Integers from Text File and Storing Into Separate Variables? (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 + ") ");

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

在 Java 中创建 File 实例以引用文本文件

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 + ") } ");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM