繁体   English   中英

Java读取数据文件中的文本,并将其保存为变量

[英]Java reading text in a data file, and saving it as a variable

我是一名学生,需要帮助才能在我的Java课堂上做作业。

我们必须使用Java读取.TXT文件,然后使用其中的字母来创建机会百分比。

我们给了一个包含吨BG,GG,BB等的文件。关键是要参与其中,然后让Java计算出BB(男孩),GB(女孩男孩)等几率。

这就是我所拥有的,我知道现在所要做的就是读取并打印文件。

我要添加什么以使其满足我的需要?

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Family
{
  public static void main(String[] args)
      throws IOException
  {
    String breakLoop;
    File file = new File("MaleFemaleInFamily.txt");
    Scanner inFile = new Scanner(file);

    while (inFile.hasNext())
    {
      breakLoop = inFile.next();
      System.out.println(breakLoop);
    }
    inFile.close();
  }
}

**希望这是您想要的。

 package NewFile_files;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;



    public class OddsCalculator {
        long bgCount;
        long ggCount;
        long bbCount;
        // set this variable's value, as the number of lines after which you want to
        // calculate odds.
        int startShowingOddsAfter = 15;

        void calculator() throws FileNotFoundException {
            String breakLoop;
            File file = new File("MaleFemaleInFamily.txt");
            Scanner inFile = new Scanner(file);
            int i = 0;
            while (inFile.hasNext()) {
                breakLoop = inFile.next();
                System.out.println(breakLoop);
                switch (breakLoop.toLowerCase()) {
                case "bb":
                    bbCount++;
                    break;
                case "bg":
                    bgCount++;
                    break;
                case "gg":
                    ggCount++;
                    break;
                default:
                    break;
                }
                if (i++ > 15)
                    oddsPrinter();

            }
            inFile.close();
        }

        private void oddsPrinter() {
            System.out.println("Odds for next word are :");
            long total = bbCount + bgCount + ggCount;
            System.out.println("To be BB : " + (bbCount * 100) / total + "%");
            System.out.println("To be BG : " + (bgCount * 100) / total + "%");
            System.out.println("To be GG : " + (ggCount * 100) / total + "%");

        }

        public static void main(String[] args) throws FileNotFoundException {
            new OddsCalculator().calculator();
        }
    }
    **strong text**

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM