基本 Java:错误:需要类、接口或枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19720747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Basic Java: Error: Class, Interface, or Enum Expected
提问by user2943817
I am trying to write a method to see if the string is a palindrome (Words that can be spelled correctly backwards too, for example "racecar". I cant find the error so maybe another set of eyes will help. Here is the code:
我正在尝试编写一种方法来查看字符串是否为回文(也可以向后正确拼写的单词,例如“racecar”。我找不到错误,所以也许另一组眼睛会有所帮助。这是代码:
public boolean isPalindrome(String str){
numberofQuestions++;
int n = str.length();
for( int i = 0; i < n/2; i++ )
if (str.charAt(i) != str.charAt(n-i-1)) return false;
return true;
}
EDIT: Screenshot of errors:
编辑:错误截图:
Start of class:
上课开始:
public class Geek{
private String name;
private int numberofQuestions=0;
Final Edit: Found an extra "{" inside one of the methods. Thanks to everyone for your help!
最终编辑:在其中一个方法中发现了一个额外的“{”。感谢大家的帮助!
回答by Reimeus
The method should be fully enclosed within a class
该方法应该完全包含在一个类中
public class Geek {
private String name;
private int numberofQuestions = 0;
public boolean isPalindrome(String str) {
numberofQuestions++;
int n = str.length();
for (int i = 0; i < n / 2; i++)
if (str.charAt(i) != str.charAt(n - i - 1))
return false;
return true;
}
}
回答by Eng.Fouad
I bet it is something related to missing braces, or braces that closes the class body before starting this method definition.
我敢打赌,这与缺少大括号或在开始此方法定义之前关闭类主体的大括号有关。
回答by Eng.Fouad
Make the isPalindrome()
function static.
使isPalindrome()
函数静态。
Here's a sample:
这是一个示例:
public class Sample {
private static int numberofQuestions;
public static void main(String[] args)
{
String str = "racecar";
String str2 = "notpalindrome";
boolean test = isPalindrome(str);
boolean test2 = isPalindrome(str2);
System.out.println(str + ": " + test);
System.out.println(str2 + ": " + test2);
}
public static boolean isPalindrome(String str) {
numberofQuestions++;
int n = str.length();
for (int i = 0; i < n / 2; i++)
if (str.charAt(i) != str.charAt(n - i - 1))
return false;
return true;
}
}
Output:
输出:
racecar: true
notpalindrome: false
回答by user2885596
You must check your curly braces that whether it is properly ended after looping , method and class.
你必须检查你的花括号是否在循环、方法和类之后正确结束。
回答by Manish Doshi
I think there is problem in curly braces. You didnt end the bracket of main class Geek{ }.
我认为花括号有问题。你没有结束主类 Geek{} 的括号。
Check this:
检查这个:
public class Geek
{
private String name;
private int numberofQuestions = 0;
public boolean isPalindrome(String str)
{
numberofQuestions++;
int n = str.length();
for (int i = 0; i < n / 2; i++)
if (str.charAt(i) != str.charAt(n - i - 1))
return false;
return true;
}
}