创建一个变量,其变量名包含来自另一个变量的值

因此,对于 while 循环,每次通过时我都会创建一个变量,将“i”分配为计数器来计算循环次数。我希望将它附加到变量的末尾,我突然想到我可能会为此使用一个对象,但这是同样的问题,这只会使问题变得更加复杂。代码如下。


import java.util.*;

import java.io.*;

/**

 * Counts composition of children's sexes among nuclear families.

 *

 * @author Thomas Morey

 * @version 10/7/18

 */

public class Family

{

    public static void main() throws IOException{

        File read = new File("C:/Users/tdmor/Desktop/Misc/School/AP Comp Science/Recources/maleFemaleInFamily.txt"); //entire file path necisary?

        Scanner inf = new Scanner(read); //stands for in file

        String family;

        int quan;

        int i = 1;

            while(inf.hasNext()){

                family = inf.next();

                String famNum/*increment here*/ = family; //create a variable with the int "i" appended to the end of the variable name to represent how many families there are.

                quan = i;

                System.out.println(family);

                i++;

            }

    }

}

因此,经过进一步思考,我可能应该解释程序的预期结果是什么。它根据孩子的性别将有两个孩子的家庭数量分类。例如,BB 是两个男孩,GG 是两个女孩,而 BG 和 GB 是不同的东西。这将输出家庭的总数以及每个家庭的数量,并带有百分位。


慕斯王
浏览 174回答 2
2回答

鸿蒙传说

考虑在List此处使用:List<String> famNum=new ArrayList();while(inf.hasNext()){&nbsp; &nbsp; family = inf.next();&nbsp; &nbsp; famNum.add(family);&nbsp; &nbsp; quan = i;&nbsp; &nbsp; System.out.println(family);&nbsp; &nbsp; i++;}

森栏

这是将计数器的变量附加到族变量末尾的示例:FileReader read = new FileReader("PATH");Scanner inf = new Scanner(read); //stands for in fileString family;int quan;int i = 1;&nbsp; &nbsp; while(inf.hasNext()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; family = inf.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String famNum = family + " " + i; //create a variable with the int "i" appended to the end of the variable name to represent how many families there are.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; quan = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(famNum);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; }这是你的输出:johnsons 1flintstons 2harrolds 3smiths 4cambells 5但是,无需创建新对象。您可以真正附加如下:family += " " + i;只需使用 += 运算符 + i。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java