2012-10-18 35 views
0

我試圖用Java編寫一個程序,該程序將接受用戶輸入並轉換爲攝氏或華氏。因此用戶輸入一些數字,一個空格,然後是C或F.禰程序編譯罰款,但是當我嘗試測試它,我得到以下信息:MSDOS窗口中的Java程序錯誤:線程「main」中的異常java.lang.NumberFormatException

Exception in thread "main" java.lang.NumberFormatException: For input string: (whatever number, space, F/C I put in to test it0 

    at java.lang.Integer.parseInt<Integer.java:492> 
    at java.lang.Integer.parseInt<Integer.java:527> 
    at Temp.Conv.main<TempConv.java:14> 

我猜的Java不像我試圖使用Parse搜索字符串中的整數。 有關如何完成它的任何建議?

下面是代碼:(只要你知道,我知道的支架和空間是關閉的,但這網站不會讓我來解決它)

public class TempConv 
{ 
public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in); 
    String reply = "y"; 
    while(reply.equalsIgnoreCase("y")) 
    { 
     System.out.println("Enter temp (ex. 70 F or 23 C): "); 
     String CF = input.nextLine(); // inputs string 
     int temp = Integer.parseInt(CF); // to get integers from string 
     for (int i = 0; i < CF.length(); ++i) 
     { 
      char aChar = CF.charAt(i); 
      if (aChar == 'F') // looking in string for F 
      // go to f2c() 
      { 
       f2c(temp); 
      } 
      else if (aChar == 'C') // looking for C 
      // go to c2f() 
      { 
       c2f(temp); 
      } 
     } 
    System.out.println("Would you like to covert another temp? <y/n> "); 
    reply = input.next(); 
    } 
} 
static void f2c(int j) 
{ 
    int c = (j - 32)*(5/9); 
    System.out.println(j + "F = " + c + "C"); 
} 

static void c2f(int k) 
{ 
    int f = (k*(5/9))+32; 
    System.out.println(k + "C = " + f + "F"); 
} 
} 

回答

1

Integer.parseInt將嘗試解析整個字符串你通過了。如果你通過例如"75F"那麼該方法將失敗,除了你看到的例外。

您需要進行自己的輸入驗證。如果您希望用戶使用某種格式,則需要檢查輸入是否與格式匹配,然後提取與該數字匹配的輸入部分,並將其傳遞至Integer.parseInt:檢查最後一個字符爲CF,並將該字符前面的子字符串傳遞給Integer.parseInt。將呼叫包裝在try/catch區塊中,以便您可以繼續詢問/循環輸入是否仍然格式錯誤。

您可以使用Scanner.nextInt從輸入搶號,但如果你輸入的樣子75F,然後Scanner.nextInt將失敗並InputMismatchException

0
String CF = input.nextLine(); // inputs string 
int temp = Integer.parseInt(CF); // 

有問題。你怎麼知道用戶總是輸入整數值?這裏它試圖解析例如10C或10F,它不是一個有效的整數。當你是nextLine方法它返回任何字符串,它不是必須的,它應該是一個數字。處理,在一個嘗試捕捉,

try { 
temp = Integer.parseInt(CF); 
} catch() { 
//handle 
} 

但即使在此之前,你必須拆分C或F由於原始字符串客場做整數解析。

相關問題