问题,我有,是我迷路了。我不知道从哪里开始这项任务。
这就是文本文件的样子
文件名是“districtpopulation”
ALABAMA,Abbeville,2955
ALABAMA,Adamsville,4771
ALABAMA,Addison,720
ALABAMA,Alabaster,28904
ALABAMA,Alexander_City,15053
ALABAMA,Aliceville,2457
ALABAMA,Andalusia,8727
ALABAMA,Anniston,23736
ALABAMA,Arab,7694
ALABAMA,Ardmore,1145
ALABAMA,Ariton,747
ALABAMA,Ashford,1967
ALABAMA,Ashland,1856
ALABAMA,Ashville,2503
ALABAMA,Atmore,7452
ALABAMA,Auburn,53160
ALABAMA,Autaugaville,885
ALABAMA,Bay_Minette,7674
ALABAMA,Bayou_La_Batre,2761
ALABAMA,Bear_Creek,1016
ALABAMA,Berry,1212
ALABAMA,Bessemer,28217
您必须实施的命令是:
•平均所有
o将所有地区的平均人口打印到控制台
•平均值
o将给定状态列表的平均人口打印到控制台
•top x all
o将所有地区人口最多的前x区打印到控制台,x是用户输入的任何正整数
•top x
o打印州内每个州的人口最多的前x个百分比 列表到控制台,x是用户输入的任何正整数
•退出
o退出程序
任何接受a的命令都必须对列表中的每个状态执行所需的操作。例如命令:
top 2 michigan new_york
应具有以下输出(数据已组成)
MICHIGAN:
Detroit: 123453
Flint: 4323532
NEW_YORK:
New_York_City: 2342342
Some_other_city: 2342342
这是我和同学一起组织的
import java.io.File;
import java.util.Scanner;
public class Database {
public static String[] data = new String[9000];
public static int count;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean keepGoing = true;
//other setup as needed
while (keepGoing) {
String command = keyboard.nextLine();
String[] commandParts = command.split(" ");
//if (commandParts[0].equalsIgnoreCase("average"))
//if (commandParts.length == 2) //do other stuff check for other things
// else if ( . .. .) {
//else if user entered in "exit"
//keepgoing = fals }
//MiChIgAN == MICHIGAN
}
}
public static void readDataFile(String fileName) throws Exception {
File dataFile = new File(fileName);
Scanner fileReader = new Scanner(dataFile);
while (fileReader.hasNextLine()) {
data[count] = fileReader.nextLine();
count++;
}
fileReader.close();
}
public static void topXAll(int x) {
//print out the top x
}
//..top state
// gettopforstate ..
public static void averageAll() {
System.out.println("my results here");
}
public static void averageList(String[] input) {
String output = "";
//for each state in state list {
//output += getAverageForState(stateName);
System.out.println(output);
}
public static String getAverageForState(String stateName) {
return "";
}
//this is how we do stuff
public static void doStuff() {
String[] parts;
for (int i = 0; i < count; i++) {
parts = data[i].split(",");
String stateName = data[0];
String districtName = data[1];
int population = Integer.parseInt(data[2]);
}
}
}
答案 0 :(得分:1)
您需要创建File
对象并检查while(keyboard.hasNext() or hasNextLine())
,而不是检查while(keepgoing)
。您应该将File
对象作为Scanner
的参数传递。当您想要从控制台读取时,会传递System.in
。
File file = new File("file.txt");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNextLine()){
String command = inputFile.nextLine();
// do something
}
另外,我在您的代码//MiChIgAN == MICHIGAN
中将其视为评论。确保您不会陷入尝试将字符串与==
进行比较的臭名昭着的陷阱。使用equals()
编辑: 此外,您可能希望使用逗号而不是空格进行拆分。文本
之间没有空格分隔符String command = keyboard.nextLine();
String[] commandParts = command.split(",");