Reputation: 25
I having an input file
First line is the size of array(N)
Second line is N element
I have to proceeded if N ==No of element in second line
For EX:
3
1 3 4 //ok
4
3 5 6 7 7 // Do nothing
My code:
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
Upvotes: 0
Views: 116
Reputation: 20244
int n = in.nextInt();
if((n*2)==(in.nextLine().length()-1))
//correct length
else
//Incorrect length
Try the above code. In the file,if integers are seperated by spaces,then it also counts as a character in length. Subtracting one from length is because the number of spaces is one less than the number of integers. Note that the above is applicable only when n>1.
Upvotes: 0
Reputation: 8361
You could use this code to read two lines. The method will return null if the size doesn't match, and the array otherwise.
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;
}
Upvotes: 0
Reputation: 4086
in.nextLine() will give you a String containing :
"1 3 4"
with 2 spaces and 3 digits. You should do :
String line = in.nextLine();
String[] digits = line.split(" ");
if (n==digits.length) {
...
Moreover be aware of the fact that using in.nextLine()
in your if condition, leads you to lost the content of the line
Upvotes: 5
Reputation: 510
I hope this helps with your question, assuming that I understood your question.
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();
}
Upvotes: 0