我是新編程的Java和涉及字符串的工作。我剛開始使用代碼模板,我的指令是編譯它並查看輸出,但是有一個錯誤提示「變量phraseLength可能沒有被初始化」。它指的是當我使用「phraseLength」作爲我的代碼底部附近的變量時。有誰知道如何解決這一問題?非常感謝你提前。如何解決「變量phraseLength可能尚未初始化」(Java)?
import java.util.Scanner;
public class Working_With_Strings
{
public static void main (String[] args)
{
//instantiate the String……
String phrase = new String ("This is a String test.");
int phraseLength;
int middle3;// number of characters in the phrase String
int middleIndex; // index of the middle character in the String
String firstHalf; // first half of the phrase String
String secondHalf; // second half of the phrase String
String switchedPhrase; // a new phrase with original halves switched
// 1-compute the length and middle index of the phrase
//2- get the substring for each half of the phrase
//3- concatenate the firstHalf at the end of the secondHalf
// print information about the phrase
System.out.println();
System.out.println ("Original phrase: " + phrase);
System.out.println ("Length of the phrase: " + phraseLength +
" characters");
System.out.println ("Index of the middle: " + middleIndex);
System.out.println ("Character at the middle index: " +
phrase.charAt(middleIndex));
System.out.println ("Switched phrase: " + switchedPhrase);
System.out.println();
}
}
我不明白錯誤是什麼意思,因爲我不知道初始化是什麼意思。現在我知道我需要用一個值初始化「phraseLength」。再次感謝你的幫助!
給它一個初始值。局部變量沒有默認值。 – Li357
[變量可能未被初始化錯誤]的可能重複(http://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – shmosel
不能使用變量沒有初始化。 – passion