我查看了所有链接,但似乎无法得到我想要的东西。我有一个需要读入的文本文件。首先是文本文件格式:
3 STL NY Chi //all on one line
STL NY 575 //on its own line
NY Chi 550 //on its own line
STL Chi 225 //on its own line
我需要将 int 读入一个 int 变量,比如我们称之为计数。然后将同一条线上的实际城市放入一个数组中。接下来的几行需要读入一个数组,以将里程与该数组相关联,例如 [STL NY]=575。我只能使用数组。没有哈希表、列表、堆栈或队列。这是我到目前为止得到的,老实说它并不多。我真的可以使用一些帮助,因为我对这方面的“操作方法”感到非常困惑。
import java.io.*;
import java.util.*;
public class P3 {
/**
* @param args the command line arguments
*/
public static int count;
public static void main(String[] args) {
try {
FileInputStream dataFile = new FileInputStream("Data.txt");
//BufferedReader br = new BufferedReader(new InputStreamReader(dataFile));
String line = br.readLine();
}
catch (IOException e) {
System.err.println ("Unable to open file");
System.exit(-1);
}
}
}
我想我到了那里,但我收到一个错误代码:“非静态变量城市无法从静态上下文中引用。” 我正在尝试通过打印来测试我的代码。谁能帮我打印这个?我想看看数组中有什么,以确保我做得正确。这是我的代码:
package p3;
import java.io.*;
import java.util.*;
class citiesDist {
String cityOne;
String cityTwo;
int miles;
}
class city {
String cityName;
int numberLinks;
citiesDist[] citiesDists;
}
public class P3 {
city[] cities;
void initCity(int len) {
for (int i = 0; i < len; i++) {
cities[i] = new city();
}
}
void initCitiesDist (int index, int len) {
for (int i = 0; i < len; i++) {
cities[index].citiesDists[i] = new citiesDist();
}
}
void parseFile() throws FileNotFoundException, IOException {
FileInputStream fstream = new FileInputStream("Data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int numberCities = Integer.parseInt(br.readLine());
cities = new city[numberCities];
initCity(numberCities);
for (int i = 0; i < numberCities; i++) {
String line = br.readLine();
int numberLink = Integer.parseInt(line.split(" ")[1]);
cities[i].cityName = line.split(" ")[0];
cities[i].numberLinks = numberLink;
initCitiesDist (i, numberLink);
for (int j = 0; j < numberLink; j++){
line = br.readLine();
cities[i].citiesDists[j].cityOne = line.split(" ")[0];
cities[i].citiesDists[j].cityTwo = line.split(" ")[1];
cities[i].citiesDists[j].miles = Integer.parseInt(line.split(" ")[2]);
}
}
}
public static void main(String args[]) {
System.out.println("city" + cities.city);
}
}