2013-09-27 63 views
1

您好,我正在創建一個算法,以獲取int x並將其轉換爲所需的基礎int y。 實施例7基體3 = 21循環中找不到符號

void printXBaseY(int x, int y) { 

    boolean active = true; 

    while(x >= y) { 
     int a = x % y; 
     int b = x/y; 


     String first = "" + a; 
     String second = "" + b; 

     String answer = "" + first + second; 

    } 

    String answer = "" + first + second; 

    println(x + " base " + y + " is " + answer); 

} 

}

在字符串回答它的主要錯誤不能找到符號 - 第一可變,任何人都可以解釋爲什麼它不能找到它?並提供解決方案。

謝謝你提前

回答

3

那些變量超出了範圍。

在java中,範圍限制爲{}

只需將它們移動到頂端,以便它們可以繼續使用。

void printXBaseY(int x, int y) { 

      boolean active = true; 
      String first=""; // or null 
      String second=""; // or null 
      while(x >= y) { 
       int a = x % y; 
       int b = x/y; 


       first = "" + a; 
       second = "" + b; 

       String answer = "" + first + second; 

      } 

      String answer = "" + first + second; 

      System.out.println(x + " base " + y + " is " + answer); 

     } 

你可能是一個初學者:瞭解更多關於block and statements

3

這是超出範圍。你在while循環中聲明它。它後來消失了。

爲了解決這個問題,在while循環開始之前聲明第一個和第二個。

0

你的第一和第二變量while循環內部聲明。所以它們的範圍在循環內部,while循環中只有你不能使用它們。下面

while(x >= y) { 
     int a = x % y; 
     int b = x/y; 


     String first = "" + a; 
     String second = "" + b; 

     String answer = "" + first + second; 



    String answer = "" + first + second; 

    println(x + " base " + y + " is " + answer); 

} 
0
while(x >= y) { 
    int a = x % y; 
    int b = x/y; 


    String first = "" + a; // here is the problem. You declared first and second within the while loop. 
    String second = "" + b; 

    String answer = "" + first + second; 

} 

更正碼的同時,通過塊邊界。所以它不能在外面訪問。

+0

我試過,但循環永遠不會結束在發佈前,謝謝雖然 – user2797454

2

的可變範圍的 「第一」

void printXBaseY(int x, int y) { 

    boolean active = true; 
    String first = null; 
    String second = null 
    while(x >= y) { 
     int a = x % y; 
     int b = x/y; 


     first = "" + a; 
     second = "" + b; 

     String answer = "" + first + second; 

    } 

    String answer = "" + first + second; 

    println(x + " base " + y + " is " + answer); 

} 
0
void printXBaseY(int x, int y) { 

    boolean active = true; 
String first="";  
String second=""; 
    String answer="";  

    while(x >= y) { 
     int a = x % y; 
     int b = x/y; 


     first = "" + a; 
     second = "" + b; 

    // answer = "" + first + second; 

    } 

    answer = "" + first + second; 

    println(x + " base " + y + " is " + answer); 

}