[英]Finding every other integer token using a Scanner for the file
所以我正在使用掃描儀作為一個包含 4 個男孩和 3 個女孩的文件示例。 在每個名字之后都有一個 integer(Mike 24),就像這樣,它以一個男孩然后女孩然后男孩然后女孩等等開始。總共有 4 個男孩和 3 個女孩,我應該計算男孩和女孩的數量和然后將每個男孩的數字加起來,然后女孩的數字相同。 另外,當我為男孩分配 console.nextInt() 時,它會從文件中獲取數字然后分配給男孩變量嗎? 另外,console.hasNext() 是否有一個索引,如果它讀取令牌 #1 那么我可以說 console.hasNext() == 1;?非常感謝。
樣本數據:
埃里克 3 麗塔 7 坦納 14 吉琳 13 柯蒂斯 4 斯蒂芬妮 12 本 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();
}
}
}
}
hasNext()
只會返回true
或false
。 首先你不應該這樣做int boys = console.nextInt();
在循環內,因為它每次都會創建新變量並且數據將丟失。 你需要做的是分配int boys = 0;
只是低於你的其他 2 個變量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 循環之后,您可以對變量執行所需的操作,例如打印它們或其他東西。 希望我能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.