private Scanner inputFile;
private String corpusFileString = "";
try
{
File file = new File(sourceFile.getText());
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "The file was found.");
if (text != null)
{
translate.setEnabled(true);
}
}
catch (FileNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "The file was not found.");
}
try
{
numberWords = inputFile.nextInt();
}
catch (InputMismatchException ex)
{
JOptionPane.showMessageDialog(null, "The first line on the file must be an integer");
}
while (inputFile.hasNext())
{
corpusFileString = corpusFileString + inputFile.nextLine() + " ";
}
所以当我读取这个文件时,第一行应该是一个整数(一个不同的变量将保存它),否则它将抛出异常。 文件的其余部分应该是数据(所有数据的另一个变量),但由于某种原因,String在开头包含一个空的空格,当我拆分它时,我必须在我的数组中使用+1,因为这个空的空间。
答案 0 :(得分:0)
使用String.Trim()删除字符串开头和结尾的空格。 链接到方法:http://msdn.microsoft.com/de-de/library/t97s7bs3(v=vs.110).aspx
答案 1 :(得分:0)
问题在于它正在读取第一个int,然后读取第一行的其余部分。
基本上:
15 \ n这里有一行\ n另一行
其中\ n是换行符。
它读取15,然后读取到\ n,这是“”(省略换行符)。其余部分按预期读取。
尝试使用:
numberWords = Integer.parseInt(inputFile.nextLine());
而不是
numberWords = inputFile.nextInt();
答案 2 :(得分:0)
我不确定java。在您尝试使用hasNext()
阅读之前,您可能需要致电nextInt()
。这就是.NET读者和枚举器的工作方式。在c#中,我会写类似
while (reader.MoveNext()) {
string s = reader.Current;
}
在您的情况下,您可以尝试
if (inputFile.hasNext()) {
numberWords = inputFile.nextInt();
}