簡體   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