使用文件的扫描程序查找所有其他整数标记

Finding every other integer token using a Scanner for the file

提问人:Micah Cave 提问时间:11/27/2021 最后编辑:DadaMicah Cave 更新时间:11/27/2021 访问量:69

问:

我正在使用一个有 4 个男孩和 3 个女孩的文件示例。每个名字后面都有一个整数(例如),它以男孩开头,然后是女孩,然后是男孩,然后是女孩,等等。总共有 4 个男孩和 3 个女孩,我应该计算男孩和女孩的数量,然后将每个男孩的数字相加,然后女孩也是如此。另外,当我分配男孩时,是否从文件中获取数字,然后分配给男孩变量?另外,是否有一个索引,例如如果它读取令牌 #1,那么我可以说?ScannerMike 24console.nextInt()console.hasNext()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();
          }
    }

  } 
}
java 文件 io java.util.scanner

评论


答:

1赞 Emad Ali 11/27/2021 #1

只会返回或 .首先,你不应该在循环中做,因为它每次都会创建新的变量,数据会丢失。您需要做的是分配其他 2 个变量,并且 也是如此hasNext()truefalseint boys = console.nextInt();int boys = 0;int boysCountint girlsCountint 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 循环之后,您可以对变量执行您想要的操作,例如打印它们或其他东西。希望我能帮上忙。

评论

0赞 Micah Cave 11/27/2021
谢谢!我已经为此工作了几天,并且正在与 Java 作斗争。