以下是我的代码,我已经发表评论来解释我面临的问题。
我应该导入别的东西吗?我正在使用jGrasp
编译器?
import java.awt.*;
import java.applet.*;
import java.lang.*;
/*this is just a test class to learn how to use substring. I was trying to use substring
to play around with strings in this case my dogs name. I was doing exercises on codingbat.com
and came across the substring method.
*/
public class Donna extends Applet {
String DogName = "Donna Peluda"; // declare the String variable DogName
String FirstDog = ""; // declare FirstDog String variable blank
FirstDog = DogName.substring( 0, 2); // I get "Donna.java:9: error: <identifier> expected"
// if I comment out line 9 it prints "Donna Peluda" ok
// Ive tried examples from the web and get the same error and spent 2 evenings on this so
public void paint(Graphics d) {
d.drawString(DogName + FirstDog ,25, 25);//print the result to the applet
}
}
答案 0 :(得分:2)
这不适合分配。 如果你真的想在那里做,那试试这个
public class Donna extends Applet
{
String dogName = "Donna Peluda";
String FirstDog = "";
{
FirstDog = DogName.substring(0, 2);
}
.
.
.
答案 1 :(得分:2)
类主体(第一个开括号和最后一个右括号之间的所有内容)只允许包含以下工件:
class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
该行
FirstDog = DogName.substring( 0, 2);
字段声明部分中不允许。您可以将该行移动到构造函数中。或者直接初始化字段:
String FirstDog = DogName.substring( 0, 2);
另请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html以获取详细参考。
答案 2 :(得分:0)
试试这个:
String DogName = "Donna Peluda";
String FirstDog = getFirst();
public String getFirst()
{
return DogName.substring( 0, 2);
}
答案 3 :(得分:0)
String DogName = "Donna Peluda";
String FirstDog = "";
FirstDog = DogName.substring( 0, 2);
但是在成员分配后可以调用{}
,所以:
String DogName = "Donna Peluda";
String FirstDog = "";
{
FirstDog = DogName.substring(0, 2);
}