[JAVA][作業] Lab7 讀檔練習
code for this book, contain lists of the 1000 most popular boy and girl names in the United States for the year 2005, as compiled by the Social Security Administration.
These are blank-delimited files where the most popular name is listed first,
the second most popular name is listed second, and so on to the 1000th most
popular name, which is listed last. Each line consists of the first name followed
by a blank space followed by the number of registered births in the year using
that name. For example the girlnames.txt file begins with:
Emily 25494
Emma 22532
... 略
如果有需要, boynames.txt and girlnames.txt 留言一下, thx
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author Shiang-Yun Yang
*/
public class Lab7 {
public static class Item { // Inner Class with no-argument constructor
public String name;
public int number;
}
public static Item[] boys = new Item[1000], girls = new Item[1000]; //index [0...999] don't forget.
public static void loadList() {
Scanner readBoy = null, readGirl = null;
try {
readBoy = new Scanner(new FileInputStream("boynames.txt"));
readGirl = new Scanner(new FileInputStream("girlnames.txt"));
} catch(FileNotFoundException e) {
System.out.println("File Not Found !");
System.exit(0);
}
for(int i = 0; i < 1000; i++) {
boys[i] = new Item();
boys[i].name = readBoy.next();
boys[i].number = readBoy.nextInt();
girls[i] = new Item();
girls[i].name = readGirl.next();
girls[i].number = readGirl.nextInt();
}
}
public static void findName(String name) {
int i, rankBoy = -1, rankGirl = -1;
for(i = 0; i < 1000; i++) {
if(name.equals(girls[i].name))
rankGirl = i;
if(name.equals(boys[i].name))
rankBoy = i;
if(rankGirl >= 0 && rankBoy >= 0)
break;
}
if(rankGirl < 0)
System.out.printf("%s is not ranked among the top 1000 girl names\n", name);
else
System.out.printf("%s is ranked %d in popularity among girls with %d namings\n", name, rankGirl+1, girls[rankGirl].number);
if(rankBoy < 0)
System.out.printf("%s is not ranked among the top 1000 boy names\n", name);
else
System.out.printf("%s is ranked %d in popularity among boys with %d namings\n", name, rankBoy+1, boys[rankBoy].number);
}
public static void main(String[] args) {
loadList();
Scanner keyboard = new Scanner(System.in);
String name;
System.out.println("Enter the name which you want to search.");
while(keyboard.hasNext()) {
name = keyboard.next();
findName(name);
System.out.println("\nEnter the name which you want to search.");
}
}
}
/*
* nextInt(), next()
* Throws:
* InputMismatchException,
* NoSuchElementException,
* IllegalStateException
*/