2017-07-27 56 views
-6

您好我有這樣的代碼中的字符串獲得最短的一句話: -訪問變量的作用域聲明一次課外

import java.util.Arrays; 

public class Kata { 
public static int findShort(String s) { 

    int shortestLocation = null; 
    String[] words = s.split(""); 
    int shortestLength=(words[0]).length(); 
    for(int i=1;i<words.length;i++){ 
    if ((words[i]).length() < shortestLength) { 
     shortestLength=(words[i]).length(); 
     shortestLocation=shortestLength; 
    } 
    } 
    int p = shortestLocation; 
    return p; 
} 
} 

它返回錯誤變量shortestLocation不能被轉換成int: -

java:6: error: incompatible types: <null> cannot be converted to int 
int shortestLocation = null; 

我的問題是你如何訪問變量的範圍,就像在這種情況下我知道什麼是錯的。變量最短的位置被定義在if語句的範圍之外,因此它只考慮初始化的值。

我該如何使初始值更改爲if語句值。這是一個範圍問題,請幫助我是初學者。

+2

錯誤消息告訴你到底發生了什麼問題。不,這與範圍無關。 –

+0

您不能將null分配給基本類型int。這與範圍 – ronhash

+0

沒有任何關係,我修復它並將值更改爲0,但現在它始終返回0。我的變量值永遠不會更改爲if語句後返回的值。 – enemy123

回答

0
import java.util.Arrays; 

public class Kata { 
public static int findShort(String s) { 

int shortestLocation = null; 

這個^^線需要被初始化爲整數......不是「空」 0是在這裏很好

String[] words = s.split(""); 
int shortestLength=(words[0]).length(); 
    for(int i=1;i<words.length;i++){ 

您的問題開始^^你從來沒有經歷過的所有單詞作爲迭代你停在i<words.length這個問題是你從i = 1開始。 for循環工作是這樣的(從這裏開始; ,直到不符合;每次都這樣做)當i=words.length條件不再滿足時。

if ((words[i]).length() < shortestLength) { 
     shortestLength=(words[i]).length(); 
     shortestLocation=shortestLength; 
    } 

    } 

int p= shortestLocation; 

沒有必要在這裏初始化p ...只是返回最短的位置。

return p; 
     } 
    } 

留下這樣

import java.util.Arrays; 

public class Kata { 
public static int findShort(String s) { 

int shortestLocation = 0; 
String[] words = s.split(""); 
int shortestLength=(words[0]).length(); 
    for(int i=0;i<words.length;i++){ 
     if ((words[i]).length() < shortestLength) { 
     shortestLength=(words[i]).length(); 
     shortestLocation=shortestLength; 
     } 

    } 

return shortestLocation; 
     } 
    } 

最終代碼請記住,得到一個「好」導致它沉重地壓的話名單

正如指出了初始化您的原始'int p'的註釋可能有助於調試。

+0

嗨,謝謝你的幫助。我有它的工作。我完全消除了'shortestLocation',並直接使用'return shortestLength'來代替它,並且它工作正常。但是我的混淆仍然存在,如果我初始化一個像x這樣的變量,並在一個單獨的代碼塊中改變它的值,例如條件語句或循環。當我將它返回到該條件塊之外時,它是否會返回我初始化的值,或者在經過該條件語句之後該值會發生變化?簡單地說,它是隨處變化還是在if語句的範圍之內? – enemy123

+0

如果變量在循環內被初始化,它被綁定到該循環的範圍,但是你並沒有這樣做,因爲你的變量是在外部初始化的,因此範圍與類相關。看看**靜態範圍規則** –

+0

@ enemy123其他我可以澄清? –