I'm working on an assignment in which I use scanners to read lines and tokens of a .txt file. I need to do some conversions and rearrange a few strings, which I have done using some helper methods. The problem is that the code is only working for every other line that it reads from the file. I think I may have messed something up somewhere in the beginning of the code. Any hints or tips on what I would need to modify? Here's what I have thusfar:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("PortlandWeather2013.txt"));
while (input.hasNextLine()) {
String header = input.nextLine();
System.out.println(header);
Scanner input2 = new Scanner(header);
while (input2.hasNextLine()){
String bottomHeader = input.nextLine();
System.out.println(bottomHeader);
String dataLines = input.nextLine();
Scanner linescan = new Scanner(dataLines);
while (linescan.hasNext()){
String station = linescan.next();
System.out.print(station+ " ");
String wrongdate = linescan.next();
String year = wrongdate.substring(0,4) ;
String day = wrongdate.substring(6);
String month = wrongdate.substring(4,6);
System.out.print(month + "/" + day + "/" + year);
double prcp = linescan.nextDouble();
System.out.print("\t "+prcpConvert(prcp));
double snwd = linescan.nextDouble();
System.out.print("\t " + snowConvert(snwd));
double snow = linescan.nextDouble();
System.out.print("\t" + snowConvert(snow));
double tmax = linescan.nextDouble();
System.out.print("\t" + tempConvert(tmax));
double tmin = linescan.nextDouble();
System.out.println("\t" + tempConvert(tmin));
}
}
}
}
public static double prcpConvert(double x){
double MM = x/1000;
double In = MM * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double snowConvert(double x){
double In = x * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double tempConvert(double x){
double celsius = x/10;
double fahrenheit = (celsius *9/5)+32;
double rounded = Math.round(fahrenheit *10)/10;
return rounded;
}
nextLine()
doesn't just fetch the last line, it also advances a line. Before your second loop you are calling nextLine()
twice causing you to advance two lines each iteration of the loop.
You can fix your problem by setting dataLines = bottomHeader
instead of calling nextLine()
again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.