2014-10-16 51 views
0

該網站是新手,並計劃在計算機科學學校使用它。我試圖在java中進行錯誤檢查,確保輸入十六進制,但是我被告知該字符串輸入未初始化。檢查輸入錯誤時變量未初始化

Scanner keyboard = new Scanner(System.in); 



String input; 


Pattern legalInput = Pattern.compile("a-fA-F0-9"); 
Matcher match = legalInput.matcher(input); 
boolean answer = match.find(); 
int counterA = 0; 
while (counterA < 1) { 
    System.out.print("Please enter a hex number:"); 
    input = keyboard.nextLine(); 
    int counter = 0; 
    while (counter < 1) { 

     if (answer == true) 
      counter++; 
     else System.out.println("Error"); 
     } counterA++; 
    } 

因爲這是我的第一個編程語言即時學習,所以失去了任何和所有的幫助是apperciated!

+1

你必須在使用前初始化方法的局部變量。在你的情況下,使用'input = null'。 – TheLostMind 2014-10-16 13:56:23

回答

0

你不能指定Matcher輸入你還沒有。

String input; 
Pattern legalInput = Pattern.compile("a-fA-F0-9"); 
// Matcher match = legalInput.matcher(input); // <-- input isn't set yet. 

移動到你while循環,剛過分配input -

input = keyboard.nextLine(); 
Matcher match = legalInput.matcher(input); // <-- now input is set. 
0

製作繩input等於什麼初始化它。

String input = null; 
0

總是初始化變量,經過你的情況這link

輸入初始化爲空或默認值。

例如:

String input=null; 

除此之外嘗試關閉資源,因爲它會創建一個Resource leak

keyboard.close();