将我的代码从从键盘读取更改为从文本文件读取

  • 本文关键字:读取 文件 文本 键盘 代码 java
  • 更新时间 :
  • 英文 :


我有一个Java程序,它可以找到尽可能小的矩形"围栏",将绵羊包围在不同的坐标上。现在,程序从键盘读取。但是我需要它从文本文件中读取。这是文本文件的内容:

5
0 0
0 5
10 5
3 3
10 0

这是我当前的代码:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class BSheep {
final static int MIN_SHEEP = 2;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nSheep = sc.nextInt();
// validate nSheep
if (nSheep < MIN_SHEEP) {
System.out.println("Invalid input! We need at least " + MIN_SHEEP + " sheep to build a fence!");
System.exit(1);
}
int xMin, xMax, yMin, yMax;
// reading the 1st coordinate, using it to initialize min, max values
xMin = xMax = sc.nextInt();
yMin = yMax = sc.nextInt();
// read the remaining coordinates
for (int i = 1; i <= nSheep - 1; i++) {
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;
}
System.out.print("Fence Coordinates: {(" + xMin + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMin + "), ");
System.out.print("(" + xMax + "," + yMax + "), ");
System.out.println("(" + xMin + "," + yMax + ") ");
} // end of main function
} // end of class definition

java BSheep

最新更新