无法从java中的静态上下文错误中引用

时间:2014-10-03 13:00:13

标签: 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);'中收到错误像这样:无法从静态上下文中引用。我该怎么做才能克服这个问题?

3 个答案:

答案 0 :(得分:0)

static方法只能调用其他static方法,因此您也需要定义splitString

public static String[] splitString(String text) {

答案 1 :(得分:0)

另一种方法是static,而splitString则不是。{/ p>

splitString声明为静态,它应该有效:

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

答案 2 :(得分:-1)

将splitString方法设为静态,以便在静态上下文中引用它。

public static String[] splitString(String text)