Reputation: 193
I have a file that looks like this:
year population
1952 120323
1953 136688
1954 161681
.... .....
I want to go in that find the year with the largest increase in population as compared to the previous year.
I tried th following code but I get a the NoSuchElementException
and I'm not sure why:
String path = "filePath";
File file = new File(filePath);
Scanner sc = new Scanner(file);
int y = 0, y1, y2, p1, p2, diff = 0;
while(sc.hasNext()){
if(sc.next().equals("year") || sc.next().equals("population")){
break;
}else{
y1 = Integer.parseInt(sc.next());
p1 = Integer.parseInt(sc.next());
y2 = Integer.parseInt(sc.next()); // this line throws the exception
p2 = Integer.parseInt(sc.next());
if(p2 - p1 > diff){
diff = y2-y1;
y = y2;
}
}
}
System.out.println(y);
Upvotes: 0
Views: 83
Reputation: 176
Not sure how your code produced NoSuchElementException error. Because you are exiting from the loop when you find "year" or "population". Hope the following code should meet your expected result.
String path = "filePath";
File file = new File (path);
Scanner scanner = new Scanner(file);
Long[][] yd = new Long[0][];
long prev = 0;
for(scanner.nextLine();scanner.hasNext();){
long year = scanner.nextLong();
long curnt = scanner.nextLong();
long diff = prev==0?prev:curnt-prev;
prev = curnt;
yd = Arrays.copyOf(yd, yd.length+1);
yd[yd.length-1] = new Long[2];
yd[yd.length-1][0] = year;
yd[yd.length-1][1] = diff;
}
Arrays.sort(yd, new Comparator<Long[]>() {
@Override
public int compare(Long[] o1, Long[] o2) {
Long diffOne = o1[1];
Long diffTwo = o2[1];
return diffTwo.compareTo(diffOne);
}
});
System.out.println("Year="+yd[0][0]+"; Difference="+yd[0][1]);
Upvotes: 1
Reputation: 2355
Try this...
String path = "filePath";
File file = new File (filePath);
Scanner sc = new Scanner(file);
long year = 0L, population = 0L, largestDiff = 0L;
while (sc.hasNext()) {
String line = sc.nextLine();
if (line.startsWith("year")) {
continue;
} else {
String[] parts = line.split(" +"); // Note the space before "+"
long currentYear = Long.parseLong(parts[0]);
long currentPopulation = Long.parseLong(parts[1]);
long diff = currentPopulation - population;
if (dif > largestDiff) {
largestDiff = diff;
year = currentYear;
}
population = currentPopulation;
}
}
System.out.println(year);
System.out.println(largestDiff);
Upvotes: 1