有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个分为两部分的问题。所以我在为一个赋值编写代码,它试图从文本文件中读取整数作为坐标。例如,我有一个名为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 + ") ");

如果我要求用户输入羊的数量并自行协调,这就是成功的代码。唯一不同的是,我不需要用户输入,我只需要一个扫描仪来读取文本文件,确定坐标,然后打印出来。如果这个冗长的问题有意义,有人能帮我吗


共 (1) 个答案

  1. # 1 楼答案

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

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

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