[英]Can't print a string on the console
我无法弄清楚为什么在编译这个简单程序时会在控制台中出现错误,该程序应该只打印一个字符串(2个单独的文件):
/*WordCount.java*/
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
public class WordCount{
private String stringToTest;
//Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
//constructor
public WordCount(){
stringToTest = "This is the string I want to test, and I'm curious to see the results.";
}//end of constructor
public String getString(){
return stringToTest;
}
System.out.printf("%s ", getString());
}//end of WordCount class
/*WordCountTest.java
WordCountTest to test the class
*/
public class WordCountTest{
public static void main(String[] args){
WordCount wordCount = new WordCount();
}
}//end of WordCountTest
这些是我得到的错误:
G:\JAVA\GUI\2015\createFrames\word_counter\test>javac *.java
WordCount.java:19: error: <identifier> expected
System.out.printf("%s", getString());
^
WordCount.java:19: error: illegal start of type
System.out.printf("%s", getString());
^
WordCount.java:19: error: <identifier> expected
System.out.printf("%s", getString());
^
WordCount.java:19: error: ';' expected
System.out.printf("%s", getString());
^
WordCount.java:19: error: illegal start of type
System.out.printf("%s", getString());
^
WordCount.java:19: error: <identifier> expected
System.out.printf("%s", getString());
^
WordCount.java:19: error: ';' expected
System.out.printf("%s", getString());
^
WordCount.java:21: error: reached end of file while parsing
}//end of WordCount class
^
8 errors
我只是创建一个对象,构造函数将字符串分配给变量,然后打印出该变量。 还是我不太明白为什么这个不编译谢谢
行System.out.printf("%s", getString());
导致错误,因为它不在您的示例的方法或构造函数中。 您可以将其放在构造函数中(如果要在其中运行):
public WordCount(){
stringToTest = "This is the string I want to test, and I'm curious to see the results.";
System.out.printf("%s", getString());
}
或使用自己的方法,例如:
public void printString() {
System.out.printf("%s", getString());
}
我怀疑是因为您的打印语句不包含在方法中。 试试下面的东西
public class WordCount{
private String stringToTest;
//Map<String,Integer> mp = new HashMap<String, Integer>();//declaring a map object
//constructor
public WordCount(){
stringToTest = "This is the string I want to test, and I'm curious to see the results.";
}//end of constructor
public String getString(){
return stringToTest;
}
public void printString() {
System.out.printf("%s ", getString());
}
}//end of WordCount class
然后您可以通过以下方式使用它
public class WordCountTest{
public static void main(String[] args){
WordCount wordCount = new WordCount();
wordCount.printString();
}
}//end of WordCountTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.