Why am i stuck in infiite loop through file? public int getDataSetSize(String fi
ID: 3702146 • Letter: W
Question
Why am i stuck in infiite loop through file?
public int getDataSetSize(String filename) throws FileNotFoundException {
samples=0;
File file = new File(filename);
Scanner input = new Scanner(file);
while (input.hasNextLine()){
if(sampleArr != null){
System.out.println("4 ");
sampleArr[samples]=input.nextLine(); //sampleArr , has each line read from file
samples++;
}
}
input.close();
System.out.println("done ");
return samples;
}
main:
package wine;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws FileNotFoundException {
DataSet train = new DataSet("wine.txt");
System.out.println(train.samples);
}
}
Explanation / Answer
The only possible reason for the infinite loop in you code is that sampleArr is NULL . As a result if condition would never become true so you wont be reading anything from the input pointer. So hasNextLine() will be true for infinite time.
If you have not initialized the sampleArr before you invoke getDataSetSize, you get this problem.
Since your code is not complete i recreated your problem with below sample code. To see the behavior please run this code with any input file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileTest {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file = new File("Transaction.txt");
Scanner input = new Scanner(file);
String[] sampleArr =null;
//String[] sampleArr =new String[2];
while (input.hasNextLine()){
if(sampleArr !=null)
System.out.println(input.nextLine());
}
}
}
So please check if sampleArr is not null to resolve the error.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.