2012-11-29 158 views
0

我有一個值列表(天氣數據),編寫列表的人在沒有值的情況下使用值「9999」進行報告。我導入的文本文件,並使用下面的代碼來獲取數據,並對其進行編輯:雙打列表打印字符串

import java.io.*; 
import java.util.*; 

public class weatherData { 

public static void main(String[] args) 
     throws FileNotFoundException{ 
    Scanner input = new Scanner(new File("PortlandWeather2011.txt")); 
    processData(input); 
} 

public static void processData (Scanner stats){ 
    String head = stats.nextLine(); 
    String head2 = stats.nextLine(); 
    System.out.println(head); 
    System.out.println(head2); 
    while(stats.hasNextLine()){ 
     String dataLine = stats.nextLine(); 
     Scanner dataScan = new Scanner(dataLine); 
     String station = null; 
     String date = null; 
     double prcp = 0; 
     double snow = 0; 
     double snwd = 0; 
     double tmax = 0; 
     double tmin = 0; 
     while(dataScan.hasNext()){ 
      station = dataScan.next(); 
      date = dataScan.next(); 
      prcp = dataScan.nextInt(); 
      snow = dataScan.nextInt(); 
      snwd = dataScan.nextInt(); 
      tmax = dataScan.nextInt(); 
      tmin = dataScan.nextInt(); 
      System.out.printf("%17s %10s %8.1f %8.1f %8.1f %8.1f %8.1f \n", station, date(date), prcp(prcp), inch(snow), inch(snwd), temp(tmax), temp(tmin)); 
     } 
    } 

} 
public static String date(String theDate){ 
    String dateData = theDate; 
    String a = dateData.substring(4,6); 
    String b = dateData.substring(6,8); 
    String c = dateData.substring(0,4); 
    String finalDate = a + "/" + b + "/" + c; 
    return finalDate; 

} 

public static double prcp(double thePrcp){ 
    double a = (thePrcp * 0.1)/25.4; 
    return a; 
} 

public static double inch(double theInch){ 
    double a = theInch/25.4; 
    if(theInch == 9999){ 
     a = 9999; 
    } 
    return a; 
} 


public static double temp(double theTemp){ 
    double a = ((0.10 * theTemp) * 9/5 + 32); 
    return a; 
} 
} 

我有走的是價值和檢查所有的時間「9999」的問題出現了,並打印出「 ----」。我不知道如何獲取double類型的值,並打印出一個String。

這段代碼取值9999,並且不做任何事情。這是我的問題所在:

public static double inch(double theInch){ 
    double a = theInch/25.4; 
    if(theInch == 9999){ 
     a = "----"; 
    } 
    return a; 
} 

如果我在這個問題中提供了大量信息,我很抱歉。如果你需要我澄清就問。謝謝你的幫助!

+0

您有什麼錯誤? – user962206

+0

@ user962206呃......希望你知道最後一段代碼片段中有什麼問題。如果你不......呃... ... – Doorknob

回答

6

您需要修改inch函數才能返回一個字符串,而不是double。

public static String inch(double theInch){ 
    if(theInch == 9999){ 
     return "----"; 
    } 
    return Double.toString(theInch/25.4); 
} 
+0

謝謝,由於某種原因,我忘記了類型鑄造。 :)很好的回答! –

2

我想第一個問題可能是你正在閱讀從Scanner所有值int,而不是double秒。例如,根據您的System.out.println()發言,我想你實際上應閱讀下面的數據類型...

 prcp = dataScan.nextDouble(); 
     snow = dataScan.nextDouble(); 
     snwd = dataScan.nextDouble(); 
     tmax = dataScan.nextDouble(); 
     tmin = dataScan.nextDouble(); 

而且,看到雖然inch()方法只會在System.out.println()線使用,您將需要將其更改爲String作爲返回類型...

public String inch(double theInch){ 
    if (theInch == 9999){ 
     return "----"; 
    } 
    return ""+(theInch/25.4); 
}