我想使用StringTokenizer設置一個逗號作爲分隔符與文件中的行,每個由一個郵編和城市(前01221,華盛頓特區)組成,但我不想第二個逗號作爲分隔符,因爲它是城市名稱的一部分。我有兩個班級,我在其中讀取郵政編碼和城市名稱,但我不知道如何正確使用標記器來設置郵政編碼和城市。我想從每個班級返回1個郵政編碼和城市的數組,因此我不想將它們組合成一個班級。我也不確定是否應該將標記器放在我的主要方法中。StringTokenizer使用
public static String[] getZipCodes (File zips, Scanner hi, int d)
{
//creating array of zip codes with the length of the number of lines
String[] zipCodes=new String[d];
//Loops through each zip code to fill the array
for (int i=0; i<d; i++)
{
zipCodes[i]=hi.next();
System.out.println(zipCodes[i]);
}
return zipCodes;
}
public static String[] getCities (File zips, Scanner hi, int d)
{
//creating array of cities
String[] cities=new String[d];
//fills array with city names, parallel to its zip code
for (int i=0; i<d; i++)
{
hi.next();
cities[i]=hi.next();
hi.nextLine();
}
return cities;
}
這裏是主要的方法:
public static void main(String[] args) throws IOException {
File zips=new File("ZipCodesCity.txt");
//Scanner to count number of lines in file
Scanner in=new Scanner(zips);
//Counting number of zip codes
int codenum=0;
while (in.hasNextLine())
{
codenum++;
}
//making a second scanner to read in the zip codes
Scanner hi= new Scanner(zips);
//initializing array of zip codes
String[]zipCodes=getZipCodes(zips, hi, codenum);
//Tokenizer
StringTokenizer wrd=new StringTokenizer(hi.nextLine(), ",");
}
我添加了一個似乎缺少的大括號;如果這是錯誤的,重新編輯。如果這是正確的,請將此評論標記爲過時。 –
如果您需要在所有情況下將字符串拆分爲兩部分,請考慮使用String.indexOf()和String.substring()。當子字符串的數量不可預測時,Tokenizer非常有用(順便說一句,您可以使用String.split()來執行相同的操作)。 –
我不知道我怎麼可以採取indexOf(0,4)的每一行,因爲我不得不說in.next()和indexOf –