我发现您无法在数组上使用字符串标记符,因为您无法将String()
转换为String[]
。经过一段时间后,我意识到如果inputFromFile方法逐行读取它,我可以逐行标记它。我只是不知道如何做到这一点,以便它返回它的标记化版本。
我假设在line=in.ReadLine();
行,我应该放StringTokenizer token = new StringTokenizer(line,",")
..但它似乎无法正常工作。
有任何帮助吗? (我必须用逗号标记)。
public class Project1 {
private static int inputFromFile(String filename, String[] wordArray) {
TextFileInput in = new TextFileInput(filename);
int lengthFilled = 0;
String line = in.readLine();
while (lengthFilled < wordArray.length && line != null) {
wordArray[lengthFilled++] = line;
line = in.readLine();
}// while
if (line != null) {
System.out.println("File contains too many Strings.");
System.out.println("This program can process only "
+ wordArray.length + " Strings.");
System.exit(1);
} // if
in.close();
return lengthFilled;
} // method inputFromFile
public static void main(String[] args) {
String[] numArray = new String[100];
inputFromFile("input1.txt", numArray);
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == null) {
break;
}
System.out.println(numArray[i]);
}// for
for (int i=0;i<numArray.length;i++)
{
Integer.parseInt(numArray[i]);
}
}// main
}// project1
答案 0 :(得分:0)
这就是我的意思:
while (lengthFilled < wordArray.length && line != null) {
String[] tokens = line.split(",");
if(tokens == null || tokens.length == 0) {
//line without required token, add whole line as it is
wordArray[lengthFilled++] = line;
} else {
//add each token into wordArray
for(int i=0; i<tokens.length;i++) {
wordArray[lengthFilled++] = tokens[i];
}
}
line = in.readLine();
}// while
也可以有其他方法。例如,您可以使用StringBuilder将所有内容作为一个大字符串读取,然后将它们拆分为所需的标记等。上述逻辑只是为了指向正确的方向。