2013-06-30 80 views
1

剛學習異常捕獲。這會產生「高度無法解析爲變量」。我想我錯過了一些至關重要的事情。在try塊內聲明的變量無法解析

import java.util.*; 

public class Step4_lab01 
{ 
    public static void main(String[] args) 
    { 
     Scanner userIn = new Scanner(System.in); 

     System.out.print("Input height: "); 
     try { 
      int height = userIn.nextInt(); 
     } 
     catch(InputMismatchException e) 
     { 
      System.out.println("ERORRORrr"); 
     } 
     System.out.print("Input width: "); 
     int width = userIn.nextInt(); 

     Rectangle rektangel1 = new Rectangle(height,width); 
     rektangel1.computeArea(); 
    } 
} 

回答

1

我想你最好更改您的代碼:

int height = 0; 
int width = 0; 
Scanner scanner = new Scanner(System.in); 

while(true){ 
try{ 
    height = scanner.nextInt(); 
    break; 
    }catch(InputMismatchException ex){ 
    System.out.println("Height must be in numeric, try again!"); 
    scanner.next(); 
    /* 
    * nextInt() read an integer then goes to next line,what if the input was not 
    * numeric, then it goes to catch, after catch it goes back to try, then reads 
    * an empty line which is also not numeric, that caused the infinity loop. 
    * next() will read this empty line first, then nextInt() reads the integer value. 
    * The problem have been solved. 
    /* 
    } 
} 

做到這一點也爲寬度,你沒有從你的代碼所期望的事情是高度 try塊內,你必須注意,它是vinailed只有嘗試塊。無論何時出門,你都無法進入。
另一件事,千萬不要忘記catch塊內的消息,強烈建議有一個有意義的消息,如果不是,那麼printStackTrace()將是偉大的。

+0

好主意!代碼雖然不適用於我。我被困在一個無限的「高度必須在數字中,再試一次!」循環。 –

+0

@BenjaminLindqvist:是的,我的錯誤看到編輯答案。 – Azad

1

在try塊外聲明變量'height',以便在塊外部可見。