taking input from a txt file and creating an array from tha taken integers
hey guys so my input file looks something like this
1
2
3
4
5
public static void main(String[] args) throws FileNotFoundException {
File data = new File("data.txt");// open file
Scanner scanner = new Scanner(data);
int index = 0;
int z = 0;
while (scanner.hasNextLine()) {
z++;
scanner.nextInt();
}
int[] numbers = new int[z];
/**ok so the code above i just use it to get the size of my array but the problem seems to be in the next part. I don't know why the values of the array are not being updated. Can someone help with why or at least hint. Thanks.
*/
{
while (scanner.hasNextLine())
{
int x = scanner.nextInt();
numbers[index] = x;
index++;
}
}
}
Re: taking input from a txt file and creating an array from tha taken integers
Yes the problem is that the iterator over you file reach the end after the first while statement, so when the code doesn't enter the second while because scanner.hasNextLine() is false.
You should reset the Scanner so that it rereads the file from the beginning
Re: taking input from a txt file and creating an array from tha taken integers
just a notice, you have an extra useless {} over the second while loop
Re: taking input from a txt file and creating an array from tha taken integers
You're right haha thanks :)
btw Reps+
Re: taking input from a txt file and creating an array from tha taken integers