我正在使用一個Scanner檔案示例,該示例有 4 個男孩和 3 個女孩。每個名字后面都有一個整數(例如Mike 24),它以一個男孩,然后是女孩,然后是男孩,然后是女孩等開頭。總共有 4 個男孩和 3 個女孩,我應該計算男孩和女孩的數量,然后加上把每個男孩的數字加起來,然后女孩也一樣。另外,當我分配男孩時,console.nextInt()是否從檔案中獲取數字然后分配給男孩變數?另外,是否console.hasNext()有一個索引,就像它讀取令牌 #1 那么我可以說console.hasNext() == 1;?
樣本資料:
Erik 3 Rita 7 Tanner 14 Jillyn 13 Curtis 4 Stefanie 12 Ben 6
代碼:
import java.util.*;
import java.io.*;
public class Lecture07 {
public static void main(String[] args) throws FileNotFoundException{
System.out.println();
System.out.println("Hello, world!");
// EXERCISES:
// Put your answer for #1 here:
// You will need to add the method in above main(), but then call it here
Scanner console = new Scanner(new File("mydata.txt"));
boyGirl(console);
}
public static void boyGirl(Scanner console) {
int boysCount = 0;
int girlsCount = 0;
while (console.hasNext()) {
if (console.hasNextInt()) {
int boys = console.nextInt();
int girls = console.nextInt();
}
else {
console.next();
}
}
}
}
uj5u.com熱心網友回復:
在hasNext()將只回傳true或false。首先你不應該int boys = console.nextInt();在回圈內做,因為它每次都會創建新變數并且資料會丟失。你需要做的是分配int boys = 0;只是波紋管你的其他兩個變數int boysCount和int girlsCount,這同樣適用于int girls = 0
接下來你將需要這樣的東西:
public static void boyGirl(Scanner console) {
int boysCount = 0; // here we asigning the variables that we gonna be using
int girlsCount = 0;
int boys = 0;
int girls = 0;
while (console.hasNext()) { // check if there is next element, it must be the name
console.next(); // consume the name, we do not want it. or maybe you do up to you
boys = console.nextInt(); // now get to the number and add it to boys
boysCount ; // increment the count by 1 to use later, since we found a boy
if (console.hasNext()) { // if statement to see if the boy above, is followed by a girl
console.next(); // do same thing we did to the boy and consume the name
girls = console.nextInt(); // add the number
girlsCount ; // increment girl
}
}
現在,在 while 回圈之后,您可以對變數執行所需的操作,例如列印它們或其他內容。希望我能有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367715.html
標籤:爪哇 文件 io java.util.scanner
下一篇:PHP查看檔案夾內容
