2014-10-03 49 views
-1

從靜態上下文錯誤引用我有一個函數如下:不能在java中

public String [] splitString(String text) { 

    int linebreaks=text.length()/80; //how many linebreaks do I need? 
    String [] newText = new String[linebreaks+1];  
    String tmpText = text; 
    String [] parts = tmpText.split(" "); //save each word into an array-element 

    //split each word in String into a an array of String text. 
    StringBuffer [] stringBuffer = new StringBuffer[linebreaks+1]; //StringBuffer is necessary because of manipulating text 
    int i=0; //initialize counter 
    int totalTextLength=0; 
    for(int k=0; k<linebreaks+1;k++) { 
     stringBuffer[k] = new StringBuffer(); 
     while(true) {    
      if (i>=parts.length) break; //avoid NullPointerException 
      totalTextLength=totalTextLength+parts[i].length(); //count each word in String    
      if (totalTextLength>80) break; //put each word in a stringbuffer until string length is >80 
      stringBuffer[k].append(parts[i]); 
      stringBuffer[k].append(" "); 
      i++; 
     } 
     //reset counter, save linebreaked text into the array, finally convert it to a string 
     totalTextLength=0; 
     newText[k] = stringBuffer[k].toString(); 
    } 
    return newText; 
}      

我打電話從另一個函數的函數,做一些計算如下:

String text = "abc"; 
String [] tmpText = splitString(text); 
for(int k=0;k<tmpText.length;k++) { 
    contentStream.beginText(); 
    contentStream.moveTextPositionByAmount(textx, texty); 
    contentStream.drawString(tmpText[k]); 
    contentStream.endText(); 
    texty = texty - 20; 
}   
contentStream.setLineWidth((float) 0.25); 

我我在這一行中得到一個錯誤'String [] tmpText = splitString(text);'像這樣:不能從靜態上下文中引用。我該怎麼做才能克服這個問題?

+0

那第二個方法是在靜態方法中? – 2014-10-03 13:02:30

+0

努力並尋找您的錯誤。堆棧溢出充滿了這樣的問題。 – 2014-10-03 13:03:11

回答

0

一個static方法只能調用其它static方法,所以你需要定義splitString這樣太:

public static String[] splitString(String text) { 
0

另一種方法是staticsplitString不是。

申報splitString靜態和它應該工作:

public static String[] splitString(String text) { 
    // ... 
} 
-1

讓您splitString方法靜態的,所以它可以在靜態上下文中引用。

public static String[] splitString(String text)