Reputation: 17
I am doing homework for my computer programming class in school and I am trying to make a program that reads from a text file and prints out numbers as simple as that. To briefly explain it, it is a program that contains information of people and the information is outputted in the order of Person, Age, IQ, Gender, and Height. So, my teacher tells us to use the information from the text file and program it to create several statistics from it, such as "give the average height," or tell "how many people have an IQ over 140," and more. The last task he wants us to do is to put all ages from oldest to youngest. Though, I am not sure where to start with such. Any help?
Code:
import java.util.*;
import java.io.*;
class getnumbersfromFile
{
public static void main (String[] args) throws IOException
{
File file = new File("dataCopy.txt"); //put the file name "data.txt" into a object of type "File"
Scanner scan = new Scanner(file); //open up the file from the last line so we can scan or extract data from it
int age = 0, count = 1, IQ = 0, gender = 0, height = 0, mcount = 0, tall = 0, genius = 0;
double averageIQ = 0, averageHeight = 0;
while (age != -1) //Ends at -1 in text file
{
System.out.println("Person " + count);
System.out.println(age);
age = scan.nextInt(); // get one line at a time from the file we opened earlier
if(age == -1)
{
break;
}
else
{
System.out.println(IQ);
IQ = scan.nextInt();
if (IQ >= 140) genius++;
averageIQ = averageIQ + IQ;
System.out.println(gender);
if (gender == 1) mcount = mcount + 1;
gender = scan.nextInt();
System.out.println(height);
height = scan.nextInt(); // print the current data from the file to the screen
averageHeight = averageHeight + height;
if (height >= 72) tall++;
count++;
}
}
scan.close();
int small = (count - tall);
if (small <= -1) small = small * -1;
System.out.println("Statistics: ");
System.out.println("People: " + count);
System.out.println("Males to females: " + mcount + ":" + (count - mcount));
System.out.println("Tall people to normal/small people: " + tall + ":" + (count - tall));
System.out.println("Average height: " + (averageHeight/count));
System.out.println("Geniuses: " + genius);
System.out.println("Average IQ: " + (averageIQ/count));
}
}
Text file (If this helps in any way; the -1 is also for the while loop to end):
26
182
1
82
69
196
1
73
16
94
1
73
61
120
0
83
27
132
0
67
10
185
0
82
49
130
1
82
27
199
1
61
68
156
1
76
76
108
0
66
-1
Upvotes: 0
Views: 46