0
I’m just wondering what is wrong with my code. If I run this code I get an error “java.utilNoSuchElementException” null?
i get this error on line java:18 which is the “population[i] = inputFile.nextInt(); I have created a file on my computer named “provinceData” as a text file with some contents inside. https://code.sololearn.com/clXSur9w55zy/?ref=app
7 ответов
+ 2
Can you show your provinceData.txt?
+ 1
String[] names = new String[10]
int[] population = new int[10];
try
String[] names;
int[] population;
+ 1
Still error? Try above
+ 1
i think because the scanner didnt find any file in C:/temp/provinceData.txt
+ 1
you cant read name with next() because you have names with space so use nextLine()
I added two }} at the end of your code
and I open file with different way, but path is correct way too
this works for me:
...
File file = new File ("input.txt");
Scanner inputFile = new Scanner(file);
// dynamically allocate the array
String [] names = new String [10];
int[] population = new int[10];
i = 0;
while (inputFile.hasNext()) {
names[i] = inputFile.nextLine(); //nextLine()
population[i] = inputFile.nextInt();
// dummy read to discard the \n for reading the next province name
inputFile.nextLine();
//System.out.println(names[i]+" "+population[i]);
i++;
}
} } //added
0
here is what is inside the file
Ontario
12891787
Quebec
7744530
Nova Scotia
935962
New Brunswick
751527
Manitoba
1196291
British Columbia
4428356
Prince Edward Island
139407
Saskatchewan
1010146
Alberta
3512368
Newfoundland and Labrador
508270
0
tried it, doesnt compile/work