2014-06-26 23 views
-3

我在編程方面有困難,我是新手,所以我會發送整個程序到目前爲止,我只是需要案例'2'的幫助!它說它無法找到符號變量數組。Java的陣列問題

import java.util.Scanner ; 
    public class jakegrimson20062582 { 

    public static void main(String[] args) { 
       // Local variable 
       int option; 
       String squareFootage; 
       int noBed; 

       Scanner input = new Scanner(System.in); 
       Scanner user_input = new Scanner(System.in); 


      // Display menu graphics 
      System.out.println(" "); 
      System.out.println("| *****Rental Menu******* |"); 
      System.out.println("|  1. Enter rental property Details  "); 
      System.out.println("|  2. Enter monthly rent (12 Months)  "); 
      System.out.println("|  3. Display Annual Rent"); 
      System.out.println("|  4. Display rental report  "); 
      System.out.println("|  5. Display Monthly rents falling below a    certain threshold  "); 
      System.out.println(" "); 
      System.out.println(" Please Select an option: "); 
      option = input.nextInt(); 

    // Switch construct 
    switch (option) { 
    case 1: 
      System.out.println("Enter Rental Details: "); 
      System.out.println("Property Code:   "); 
      String propertyCode = user_input.next(); 
      System.out.println("Property Type:   "); 
      String propertyType = user_input.next(); 
      System.out.println("Square Footage:   "); 
      squareFootage = user_input.next(); 
      System.out.println("Number Of bedrooms  "); 
      noBed = input.nextInt(); 
      break; 


     case 2: 
{ 
      Scanner keyboardScanner = new Scanner(System.in); 
      int[] array; 
      array = new int[12]; 



      // creates for loop 
      for (int i=0; i<12; i++) 
      { 
      System.out.println("Enter Rental for month"); 
      array[i] = keyboardScanner.nextInt(); 
      } 

      for (int i=0; i<array.length; i++) 
     { 
     System.out.println(array[i]); 
     } 

} 



     System.out.println(""); 
    break; 

    case 3: 
     System.out.println("Exit selected"); 

     break; 
    default: 
     System.out.println("Invalid selection"); 
     break; 

    } 
} 
} 

我需要與完成這個代碼的幫助,眼前這個ISSUE都有助於在完成的代碼將不勝感激,因爲在題目我有使用數組的一般問題,我可能需要一個字符串這個代碼的版本,而不是INT,因爲數字有一個小數點。謝謝!

回答

2

縮進你的代碼是人類可讀的:

case 2: 
{ 
    Scanner keyboardScanner = new Scanner(System.in); 
    int[] array; 
    array = new int[12]; 

    // creates for loop 
    for (int i=0; i<12; i++) { 
     System.out.println("Enter Rental for month"); 
     array[i] = keyboardScanner.nextInt(); 
    } 
} 

// prints i in the for loop 

for (int i=0; i<array.length; i++) { 
    System.out.println(array[i]); 
} 

這使得錯誤很多更加明顯。您正在使用某些花括號{}case 2塊中創建代碼塊,並且您在該塊的內聲明您的array變量。這意味着該變量僅限於該塊。然後嘗試訪問該塊之外的變量,該塊不再存在。

應該說for循環是裏面的{}塊嗎?或者也許該塊的大括號可以完全省略,因爲case不需要它們?

+0

啊..是的..它當然應該是。 *嘆*我怎麼錯過了。 –

+1

我認爲你可以根據需要在'case'後面添加儘可能多的語句,但這一部分沒有問題。儘管'array'訪問超出了範圍。 – biziclop

+0

@biziclop:有趣的是,我想也許'{}'可能會把我扔掉。 (我的Java有點生疏。)那些只是封裝了一個塊而與'case'無關呢?我會更新答案... – David

0

使用正確的格式,所以你可以看到你的情況2結束。數組變量只存在於情況2中,並且您試圖在該範圍之外使用它。