本文介绍了为什么这个程序错了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main(String [] args) throws IOException
{
Scanner inFile = new Scanner(new File("MaleFemaleInFamily.txt"));
String token = "";
int counter = 0;
int girlAndBoy = 0;
int twoBoys = 0;
int twoGirls = 0;
while(inFile.hasNext())
{
token = inFile.next();
System.out.println(counter + "\t" + token + " ");
if(token.equals("GB"))
{
girlAndBoy++;
}
else if(token.equals("BB"))
{
twoBoys++;
}
else if(token.equals("GG"))
{
twoGirls++;
}
counter++;
}
int gbPercent = (girlAndBoy * 100) / counter;
int bbPercent = (twoBoys * 100) / counter;
int ggPercent = (twoGirls * 100) / counter;
System.out.println("\n");
System.out.println("GB: " + girlAndBoy + " \\ " + gbPercent + "%");
System.out.println("BB: " + twoBoys + " \\ " + bbPercent + "%");
System.out.println("GG: " + twoGirls + " \\ " + ggPercent + "%");
System.out.print("GB + " + "BB + " + "GG " + "= ");
System.out.println(girlAndBoy + twoBoys + twoGirls);
inFile.close();
}
}
我写了这段代码,了解GB,BB和GG出现了多少次在一个文件中。
我让程序计算总数和三个人但是我得到了每个人的个人数,但是他们没有增加总数。我做错了什么?
注意:源代码是java。
I wrote this code to find out how many times GB, BB, and GG appeared in a file.
I made the program count the total and the three individuals but then I get the individual count for each but they don't add to the total. What am I doing wrong?
Note: The source code is java.
推荐答案
public static void main(String [] args) throws IOException
{
Scanner inFile = new Scanner(new File("MaleFemaleInFamily.txt"));
String token = "";
int counter = 0;
int girlAndBoy = 0;
int twoBoys = 0;
int twoGirls = 0;
int other = 0;
while(inFile.hasNext())
{
token = inFile.next();
System.out.println(counter + "\t" + token + " ");
if(token.equals("GB"))
{
girlAndBoy++;
}
else if(token.equals("BB"))
{
twoBoys++;
}
else if(token.equals("GG"))
{
twoGirls++;
}else
{
other++;
}
counter++;
}
int gbPercent = (girlAndBoy * 100) / counter;
int bbPercent = (twoBoys * 100) / counter;
int ggPercent = (twoGirls * 100) / counter;
int otherPercent = (other * 100) / counter;
System.out.println("\n");
System.out.println("GB: " + girlAndBoy + " \\ " + gbPercent + "%");
System.out.println("BB: " + twoBoys + " \\ " + bbPercent + "%");
System.out.println("GG: " + twoGirls + " \\ " + ggPercent + "%");
System.out.println("Other: " + other + " \\ " + otherPercent + "%");
System.out.print("GB + " + "BB + " + "GG " + "OTHER" + "= ");
System.out.println(girlAndBoy + twoBoys + twoGirls +other);
inFile.close();
}
这篇关于为什么这个程序错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!