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 + ") ");
如果我要求用户输入羊的数量并自己坐标,这就是成功的代码。唯一的区别是我不想要用户输入,我只想要一个扫描仪来读取文本文件,确定坐标,然后打印出来。如果这个冗长的问题有道理,任何人都可以帮助我吗?
解决方案
在 Java 中创建 File 实例以引用文本文件
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 + ") } ");
推荐阅读
- html - 如何将 fa awesome 图标添加到引导按钮
- java - JAVA-写入文件时出现问题,但程序无法完成
- angular - 访问音频播放器的主题内容 Angular
- jquery - 如何获取数据 ID 值 onchange(文本框)
- mongodb - 尝试从命名空间“MongoDB\Driver\Monitoring”加载接口“CommandSubscriber”
- c# - 如何在 C# 中将每个新连接的对象添加到每个对象的列表中?
- r - 如何使用 R 代码从 4 个文件夹中创建一个大型 .csv 文件,每个文件夹包含 100 个文件?
- linq - EF Core 3.1 中的 Group By 和 To 字典
- javascript - javascript: 命名的 Firebase 应用程序已存在 (app/duplicate-app)
- node.js - 使用 Node 和 Axios 处理网络超时