我有一个输入文件
第一行是数组的大小(N)
第二行是N元素
如果N ==No of element in second line
我必须继续
对于EX:
3
1 3 4 //ok
4
3 5 6 7 7 // Do nothing
我的代码:
Scanner in = new Scanner(new FileReader("ok.txt"));
int n = in.nextInt();
if(n==in.nextLine().length())
// MAke an array of element
in.nextLine().length() Is not giving me a correct length i.e 3 and 5
答案 0 :(得分:5)
in.nextLine()将为您提供一个包含以下内容的字符串:
"1 3 4"
有2个空格和3个数字。 你应该这样做:
String line = in.nextLine();
String[] digits = line.split(" ");
if (n==digits.length) {
...
此外,请注意在if条件中使用in.nextLine()
会导致您丢失该行的内容
答案 1 :(得分:0)
我希望这有助于你的问题,假设我理解你的问题。
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader("yourFile.txt"));
int array_size = Integer.parseInt(reader.readLine());
String[] array = reader.readLine().split("\\s+");
if(array_size == array.length){
//continue
}
}catch(Exception ex){
ex.printStackTrace();
}
答案 2 :(得分:0)
您可以使用此代码读取两行。如果大小不匹配,该方法将返回null,否则返回数组。
public String[] readTwoLines (BufferedReader in)
{
int length = Integer.parseInt(in.readLine());
String[] ints = in.readLine().split("\\s+");
if (ints.length == length) return ints;
return null;
}
答案 3 :(得分:0)
int n = in.nextInt();
if((n*2)==(in.nextLine().length()-1))
//correct length
else
//Incorrect length
试试上面的代码。在文件中,如果整数由空格分隔,那么它也算作长度的字符。从长度中减去一个是因为空格的数量比整数的数量少一个。请注意,以上仅适用于n> 1。