我想使用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 –