As you can see, the code public Circle(double r)…. how is that
different from what I did in mine with public CircleR(double r)? For
whatever reason, no error is given in the code from the book, however
mine says there is an error there.
When defining constructors of a class, they should have the same name as its class.
Thus the following code
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
....
}
is correct while your code
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from
public CircleR(double r)
to
public Circle(double r)
or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.
So your new class should be
public class CircleR
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public double diameter()
{
double d = radius * 2;
return d;
}
}
I also added the return type double in your method as pointed out by Froyo and John B.
Refer to this article about constructors.
HTH.
In this post, we will see how to resolve invalid method declaration; return type required.
There can be multiple reasons for invalid method declaration; return type required issue.
Table of Contents
- Missing method return type
- Solution
- Missing comma in enum
- Solution
- Using different name for constructor
- Solution
Missing method return type
It is quite clear from error message that you are missing return type of the method. If you don’t want to return anything from the method, then you should set it’s return type of void.
Let’s understand with the help of example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class Employee { String name; int age; public Employee(String name) { this.name = name; } public setEmployeeDetails(String name,int age) { this.name=name; this.age=age; } } |
You will get compilation error at line 13 with error invalid method declaration; return type required.
Solution
In method setEmployeeDetails(), we did not specified return type. If it is not returning anything then its return type should be void.
Let’s change following linepublic setEmployeeDetails(String name,int age)
topublic void setEmployeeDetails(String name,int age)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class Employee { String name; int age; public Employee(String name) { this.name = name; } public void setEmployeeDetails(String name,int age) { this.name=name; this.age=age; } } |
Above code should compile fine now.
Missing comma in enum
This might sound strange but you can get this error when you are missing comma between enum type.
Let’s see with the help of example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public enum Number { One(1); Two(2); private final int num; Number(int i) {; this.num=i; } public int getNumber() { return num; } } |
C:UsersArpitDesktop>javac Number.java
Number.java:6: error: invalid method declaration; return type required
Two(2);
^
Number.java:6: error: illegal start of type
Two(2);
^
2 errors
Solution
If you notice enum types are not separated by the comma and this is the reason for this error.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public enum Number { One(1), Two(2); private final int num; Number(int i) {; this.num=i; } public int getNumber() { return num; } } |
C:UsersArpitDesktop>javac Number.java
C:UsersArpitDesktop>
As you can see error is resolved now.
Using different name for constructor
As you might know that constructor name should be same as class name in java. You might have put different name in constructor.
Let’s understand with the help of example:
|
package org.arpit.java2blog; public class Employee { String name; int age; public EmployeeN(String name) { this.name = name; } } |
You will get compilation error at line 9 with error invalid method declaration; return type required.
Solution
As you can see, constructor name is different than class name.
Let’s change following linepublic EmployeeN(String name) {
topublic Employee(String name) {
This will fix compilation error.
That’s all about invalid method declaration; return type required in java.
Invalid method declaration; return type required. This type of error occurs in Java when you declare a function and don’t mention its return type.
Let’s follow up on the basics of functions and methods in Java.
Fix Invalid method declaration; return type required in Java
You need to understand how to name and define methods in Java.
Let’s take a simple example of declaring a function. Our function will add two numbers, and it will return the answer, which will be of an integer value.
public int addTwoNumbers(int a, int b)
{
return a+b;
}
public is a reserved keyword in Java used to tell the member’s access. In this instance, it is public.
This keyword is followed by the return type of the method/function. In this case, it is int. Then you write the function’s name, and it can be any word of your choice provided it’s not a reserved keyword.
The above function will work just fine, and you will not receive any errors. But the error invalid method declaration; return type required occurs when you miss adding the function’s return type.
You can solve this by writing void instead of the return type. The void suggests that the function will not return any value.
Avoid the following code:
public void displaystring(String A)
{
System.out.println(A);
return A;//wrong way
}
As the above method is a void function, it cannot return a value. When you need to perform certain tasks, you use void functions, but you don’t require any value.
The correct way to write the above code is given below.
public void displaystring(String A)
{
System.out.println(A);
}
Here’s the complete self-explanatory code.
public class Main
{
public static void main(String args[])
{
// invalid method declaration; return type required This
// Error Occurs When you Declare A function did not mention any return type.
// there are only two options.
// if Function Did Not Return Any Value void Keyword should be used.
// void function always tell the compiler this function will return nothing..
Print();
Print1();
}
// e.g of void function...........
public static void Print()
{
System.out.println(" I am Void Function");
}
// e.g of non void Function............
public static int Print1()
{
System.out.println(" I am Non Void Function");
return 3;
}
}
Output:
I am Void Function
I am Non Void Function
In this post, I will be sharing how to fix invalid method declaration; return type required error. This error is mostly faced by Java beginners. This error generally occurs when the name of the constructor is different from the name of the class or missing method return type. Let’s dive deep into the topic:
Read Also:
Error: Identifier expected
[Fixed] Error: invalid method declaration; return type required
Example 1: Producing the error by using a different name for the constructor
Consider the following code:
public class HelloWorld {public HelloWorld1(){
} public static void main(String args[]) { System.out.println("Constructor name is different than the Class name"); } }
When you compile the above code, you will get the following compilation error:
Output:
/HelloWorld.java:3: error: invalid method declaration; return type required
public HelloWorld1(){
^
1 error
Explanation
If you observe the code, then you will find that the name of the constructor is different from the name of the class. Hence, the compilation error. The above error can be fixed by defining the constructor having the same name as its class as shown below.
Solution
public class HelloWorld {public HelloWorld(){
} public static void main(String args[]) { System.out.println("Constructor name is different than the Class name"); } }
Output:
Constructor name is different than the Class name
Example 2: Producing the error by missing method return type
Consider the following code:
public class HelloWorld { // Missing return typepublic printName(){
System.out.println("JavaHungry"); } public static void main(String args[]) { HelloWorld obj = new HelloWorld(); obj.printName(); } }
When you will compile the above code using the javac command, you will get the following compilation error:
Output:
/HelloWorld.java:4: error: invalid method declaration; return type required
public printName(){
^
1 error
Explanation
If you observe the code, then you will find that the return type of the method printName() is missing. Hence, the compilation error. The above error can be fixed by adding the return type in the method signature. Since method printName() does not return anything, hence, its return type is void.
Solution
public class HelloWorld {public void printName(){
System.out.println("JavaHungry"); } public static void main(String args[]) { HelloWorld obj = new HelloWorld(); obj.printName(); } }
Output:
JavaHungry
Example 3: Producing the error by missing comma in enum
Consider the below code:
public class EnumExample { public enum Company {APPLE("iPhone");
SAMSUNG("Galaxy"); private final String model; private Company(String model) { this.model = model; } } public static void main(String args[]){ for(Company c : Company.values()) System.out.println(c); } }
When you compile the above class using the javac command i.e javac EnumExample.java, then you will find the following compilation error:
Output:
/EnumExample.java:4: error: invalid method declaration; return type required
SAMSUNG(«Galaxy»);
^
/EnumExample.java:4: error: illegal start of type
SAMSUNG(«Galaxy»);
^
2 errors
Explanation
If you observe the code, then you will find that the comma is missing in the enum Company. Since enum types should be separated by the comma, that is not the case here. Hence, the compilation error. The above error can be fixed by adding the comma in the enum as shown below.
Solution
public class EnumExample { public enum Company {APPLE("iPhone"),
SAMSUNG("Galaxy"); private final String model; private Company(String model) { this.model = model; } } public static void main(String args[]){ for(Company c : Company.values()) System.out.println(c); } }
Output:
APPLE
SAMSUNG
That’s all for today, please mention in the comments in case you know any other way of solving invalid method declaration; return type required error.
оригинал:50 Common Java Errors and How to Avoid Them (Part 1)
Автор:Angela Stringfellow
перевод: Гусь напуган
Примечание переводчика: в этой статье представлены 20 распространенных ошибок компилятора Java. Каждая ошибка включает фрагменты кода, описания проблем и предоставляет ссылки по теме, которые помогут вам быстро понять и решить эти проблемы. Ниже приводится перевод.
При разработке программного обеспечения Java вы можете столкнуться со многими типами ошибок, но большинства из них можно избежать. Мы тщательно отобрали 20 наиболее распространенных ошибок программного обеспечения Java, включая примеры кода и руководства, которые помогут вам решить некоторые распространенные проблемы с кодированием.
Чтобы получить дополнительные советы и рекомендации по написанию программ на Java, вы можете загрузить наш «Comprehensive Java Developer’s Guide«Эта книга содержит все, что вам нужно, от всевозможных инструментов до лучших веб-сайтов и блогов, каналов YouTube, влиятельных лиц в Twitter, групп в LinkedIn, подкастов, мероприятий, которые необходимо посетить, и многого другого.
Если вы используете .NET, прочтите нашРуководство по 50 наиболее распространенным программным ошибкам .NETЧтобы избежать этих ошибок. Но если ваша текущая проблема связана с Java, прочтите следующую статью, чтобы понять наиболее распространенные проблемы и способы их решения.
Ошибка компилятора
Сообщения об ошибках компилятора создаются, когда компилятор выполняет код Java. Важно, что компилятор может выдавать несколько сообщений об ошибках для одной ошибки. Так что исправьте ошибку и перекомпилируйте, что может решить многие проблемы.
1. “… Expected”
Эта ошибка возникает, когда в коде чего-то не хватает. Обычно это происходит из-за отсутствия точки с запятой или закрывающей скобки.
private static double volume(String solidom, double alturam, double areaBasem, double raiom) {
double vol;
if (solidom.equalsIgnoreCase("esfera"){
vol=(4.0/3)*Math.pi*Math.pow(raiom,3);
}
else {
if (solidom.equalsIgnoreCase("cilindro") {
vol=Math.pi*Math.pow(raiom,2)*alturam;
}
else {
vol=(1.0/3)*Math.pi*Math.pow(raiom,2)*alturam;
}
}
return vol;
}
Обычно это сообщение об ошибке не указывает точное местонахождение проблемы. Чтобы найти проблему, вам необходимо:
- Убедитесь, что все открывающие скобки имеют соответствующие закрывающие скобки.
- Посмотрите на код перед строкой, обозначенной ошибкой. Эта ошибка обычно обнаруживается компилятором в более позднем коде.
- Иногда некоторые символы (например, открывающая скобка) не должны быть первыми в коде Java.
Примеры:Ошибка из-за отсутствия скобок。
2. “Unclosed String Literal”
Если в конце строки отсутствует кавычка, создается сообщение об ошибке «Незамкнутый строковый литерал», и это сообщение отображается в строке, где произошла ошибка.
public abstract class NFLPlayersReference {
private static Runningback[] nflplayersreference;
private static Quarterback[] players;
private static WideReceiver[] nflplayers;
public static void main(String args[]){
Runningback r = new Runningback("Thomlinsion");
Quarterback q = new Quarterback("Tom Brady");
WideReceiver w = new WideReceiver("Steve Smith");
NFLPlayersReference[] NFLPlayersReference;
Run();// {
NFLPlayersReference = new NFLPlayersReference [3];
nflplayersreference[0] = r;
players[1] = q;
nflplayers[2] = w;
for ( int i = 0; i < nflplayersreference.length; i++ ) {
System.out.println("My name is " + " nflplayersreference[i].getName());
nflplayersreference[i].run();
nflplayersreference[i].run();
nflplayersreference[i].run();
System.out.println("NFL offensive threats have great running abilities!");
}
}
private static void Run() {
System.out.println("Not yet implemented");
}
}
Обычно эта ошибка возникает в следующих ситуациях:
- Строка не заканчивается кавычками. Это легко изменить, просто заключите строку в указанные кавычки.
- Строка превышает одну строку. Длинную строку можно разделить на несколько коротких строк и соединить знаком плюс («+»).
- Кавычки, являющиеся частью строки, не экранируются обратной косой чертой («»).
Прочтите эту статью:Сообщение об ошибке незакрытой строки。
3. “Illegal Start of an Expression”
Есть много причин для ошибки «Незаконное начало выражения». Это стало одним из наименее полезных сообщений об ошибках. Некоторые разработчики думают, что это вызвано плохим запахом кода.
Обычно выражение создается для генерации нового значения или присвоения значений другим переменным. Компилятор ожидает найти выражение, но посколькуГрамматика не оправдывает ожиданийВыражение не найдено. Эту ошибку можно найти в следующем коде.
} // добавляем сюда
public void newShape(String shape) {
switch (shape) {
case "Line":
Shape line = new Line(startX, startY, endX, endY);
shapes.add(line);
break;
case "Oval":
Shape oval = new Oval(startX, startY, endX, endY);
shapes.add(oval);
break;
case "Rectangle":
Shape rectangle = new Rectangle(startX, startY, endX, endY);
shapes.add(rectangle);
break;
default:
System.out.println("ERROR. Check logic.");
}
}
} // удаляем отсюда
}
Прочтите эту статью:Как устранить ошибки «неправильное начало выражения»。
4. “Cannot Find Symbol”
Это очень распространенная проблема, потому что все идентификаторы в Java должны быть объявлены до их использования. Эта ошибка возникает из-за того, что компилятор не понимает значения идентификатора при компиляции кода.
Сообщение об ошибке «Не удается найти символ» может иметь множество причин:
- Написание объявления идентификатора может не соответствовать написанию, используемому в коде.
- Переменная никогда не объявлялась.
- Переменная не объявлена в той же области видимости.
- Никакие классы не импортируются.
Прочтите эту статью:Обсуждение ошибки «не удается найти символ»。
5. “Public Class XXX Should Be in File”
Если класс XXX и имя файла программы Java не совпадают, будет сгенерировано сообщение об ошибке «Открытый класс XXX должен быть в файле». Только когда имя класса и имя файла Java совпадают, код может быть скомпилирован.
package javaapplication3;
public class Robot {
int xlocation;
int ylocation;
String name;
static int ccount = 0;
public Robot(int xxlocation, int yylocation, String nname) {
xlocation = xxlocation;
ylocation = yylocation;
name = nname;
ccount++;
}
}
public class JavaApplication1 {
public static void main(String[] args) {
robot firstRobot = new Robot(34,51,"yossi");
System.out.println("numebr of robots is now " + Robot.ccount);
}
}
Чтобы решить эту проблему, вы можете:
- Назовите класс и файл с тем же именем.
- Убедитесь, что два имени всегда совпадают.
Прочтите эту статью:Примеры ошибки «Открытый класс XXX должен быть в файле»。
6. “Incompatible Types”
«Несовместимые типы» — это логические ошибки, которые возникают, когда операторы присваивания пытаются сопоставить типы переменных и выражений. Обычно эта ошибка возникает при присвоении строки целому числу и наоборот. Это не синтаксическая ошибка Java.
test.java:78: error: incompatible types
return stringBuilder.toString();
^
required: int
found: String
1 error
Когда компилятор выдает сообщение «несовместимые типы», решить эту проблему действительно непросто:
- Используйте функции преобразования типов.
- Разработчикам может потребоваться изменить исходные функции кода.
Взгляните на этот пример:Присвоение строки целому числу приведет к ошибке «несовместимые типы».。
7. “Invalid Method Declaration; Return Type Required”
Это сообщение об ошибке означает, что тип возвращаемого значения метода не объявлен явно в объявлении метода.
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
Есть несколько ситуаций, которые вызывают ошибку «недопустимое объявление метода; требуется тип возвращаемого значения»:
- Забыл объявить тип.
- Если метод не имеет возвращаемого значения, вам необходимо указать «void» в качестве возвращаемого типа в объявлении метода.
- Конструктору не нужно объявлять тип. Однако, если в имени конструктора есть ошибка, компилятор будет рассматривать конструктор как метод без указанного типа.
Взгляните на этот пример:Проблема именования конструктора вызывает проблему «недопустимое объявление метода; требуется тип возвращаемого значения».。
8. “Method in Class Cannot Be Applied to Given Types”
Это сообщение об ошибке более полезно, оно означает, что метод был вызван с неправильными параметрами.
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
При вызове метода вы должны передать те параметры, которые определены в его объявлении. Пожалуйста, проверьте объявление метода и вызов метода, чтобы убедиться, что они совпадают.
Это обсуждение иллюстрируетОшибки Java, вызванные несовместимостью объявлений методов и параметров в вызовах методов。
9. “Missing Return Statement”
Когда в методе отсутствует оператор возврата, выдается сообщение об ошибке «Отсутствует оператор возврата». Метод с возвращаемым значением (тип, не являющийся недействительным) должен иметь оператор, который возвращает значение, чтобы значение можно было вызвать вне метода.
public String[] OpenFile() throws IOException {
Map<String, Double> map = new HashMap();
FileReader fr = new FileReader("money.txt");
BufferedReader br = new BufferedReader(fr);
try{
while (br.ready()){
String str = br.readLine();
String[] list = str.split(" ");
System.out.println(list);
}
} catch (IOException e){
System.err.println("Error - IOException!");
}
}
Есть несколько причин, по которым компилятор выдает сообщение «отсутствует оператор возврата»:
- Оператор возврата был опущен по ошибке.
- Метод не возвращает никакого значения, но тип не объявлен как недействительный в объявлении метода.
пожалуйста, проверьтеКак устранить ошибку «отсутствует отчет о возврате»Это пример.
10. “Possible Loss of Precision”
Когда информация, присвоенная переменной, превышает верхний предел, который может нести переменная, выдается ошибка «Возможная потеря точности». Как только это произойдет, часть информации будет отброшена. Если это не проблема, переменную следует явно объявить в коде как новый тип.
Ошибка «возможная потеря точности» обычно возникает в следующих ситуациях:
- Попробуйте присвоить переменной целочисленного типа действительное число.
- Попробуйте присвоить данные типа double переменной целочисленного типа.
Основные типы данных в JavaОбъясняет характеристики различных типов данных.
11. “Reached End of File While Parsing”
Это сообщение об ошибке обычно появляется, когда в программе отсутствует закрывающая фигурная скобка («}»). Иногда эту ошибку можно быстро исправить, добавив закрывающую скобку в конце кода.
public class mod_MyMod extends BaseMod
public String Version()
{
return "1.2_02";
}
public void AddRecipes(CraftingManager recipes)
{
recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
"#", Character.valueOf('#'), Block.dirt
});
}
Приведенный выше код приведет к следующей ошибке:
java:11: reached end of file while parsing }
Инструменты кодирования и правильные отступы кода могут упростить поиск этих несоответствующих фигурных скобок.
Прочтите эту статью:Отсутствие фигурных скобок вызовет сообщение об ошибке «достигнут конец файла при синтаксическом анализе».。
12. “Unreachable Statement”
Когда оператор появляется в месте, где он не может быть выполнен, выдается ошибка «Недоступный оператор». Обычно это делается после оператора break или return.
for(;;){
break;
... // unreachable statement
}
int i=1;
if(i==1)
...
else
... // dead code
Обычно эту ошибку можно исправить, просто переместив оператор return. Прочтите эту статью:Как исправить ошибку «Недостижимый отчет»。
13. “Variable Might Not Have Been Initialized”
Если локальная переменная, объявленная в методе, не инициализирована, возникнет такая ошибка. Такая ошибка возникает, если вы включаете переменную без начального значения в оператор if.
int x;
if (condition) {
x = 5;
}
System.out.println(x); // x не может быть инициализирован
Прочтите эту статью:Как избежать появления ошибки «Возможно, переменная не была инициализирована»。
14. “Operator … Cannot be Applied to ”
Эта проблема возникает, когда оператор действует с типом, который не входит в область его определения.
operator < cannot be applied to java.lang.Object,java.lang.Object
Эта ошибка часто возникает, когда код Java пытается использовать строковые типы в вычислениях (вычитание, умножение, сравнение размеров и т. Д.). Чтобы решить эту проблему, вам необходимо преобразовать строку в целое число или число с плавающей запятой.
Прочтите эту статью:Почему нечисловые типы вызывают ошибки программного обеспечения Java。
15. “Inconvertible Types”
Когда код Java пытается выполнить недопустимое преобразование, возникает ошибка «Неконвертируемые типы».
TypeInvocationConversionTest.java:12: inconvertible types
found : java.util.ArrayList<java.lang.Class<? extends TypeInvocationConversionTest.Interface1>>
required: java.util.ArrayList<java.lang.Class<?>>
lessRestrictiveClassList = (ArrayList<Class<?>>) classList;
^
Например, логические типы нельзя преобразовать в целые числа.
Прочтите эту статью:Как преобразовывать неконвертируемые типы в программном обеспечении Java。
16. “Missing Return Value”
Если оператор возврата содержит неверный тип, вы получите сообщение «Отсутствует возвращаемое значение». Например, посмотрите на следующий код:
public class SavingsAcc2 {
private double balance;
private double interest;
public SavingsAcc2() {
balance = 0.0;
interest = 6.17;
}
public SavingsAcc2(double initBalance, double interested) {
balance = initBalance;
interest = interested;
}
public SavingsAcc2 deposit(double amount) {
balance = balance + amount;
return;
}
public SavingsAcc2 withdraw(double amount) {
balance = balance - amount;
return;
}
public SavingsAcc2 addInterest(double interest) {
balance = balance * (interest / 100) + balance;
return;
}
public double getBalance() {
return balance;
}
}
Возвращается следующая ошибка:
SavingsAcc2.java:29: missing return value
return;
^
SavingsAcc2.java:35: missing return value
return;
^
SavingsAcc2.java:41: missing return value
return;
^
3 errors
Обычно эта ошибка возникает из-за того, что оператор return ничего не возвращает.
Прочтите эту статью:Как избежать ошибки «Отсутствует возвращаемое значение»。
17. “Cannot Return a Value From Method Whose Result Type Is Void”
Эта ошибка Java возникает, когда метод void пытается вернуть какое-либо значение, например, в следующем коде:
public static void move()
{
System.out.println("What do you want to do?");
Scanner scan = new Scanner(System.in);
int userMove = scan.nextInt();
return userMove;
}
public static void usersMove(String playerName, int gesture)
{
int userMove = move();
if (userMove == -1)
{
break;
}
Обычно эту проблему может решить изменение типа возвращаемого значения метода, чтобы он соответствовал типу в операторе возврата. Например, следующий void можно изменить на int:
public static int move()
{
System.out.println("What do you want to do?");
Scanner scan = new Scanner(System.in);
int userMove = scan.nextInt();
return userMove;
}
Прочтите эту статью:Как исправить ошибку «Невозможно вернуть значение из метода, тип результата которого недействителен»。
18. “Non-Static Variable … Cannot Be Referenced From a Static Context”
Эта ошибка возникает, когда компилятор пытается получить доступ к нестатической переменной в статическом методе:
public class StaticTest {
private int count=0;
public static void main(String args[]) throws IOException {
count++; //compiler error: non-static variable count cannot be referenced from a static context
}
}
Чтобы устранить ошибку «Нестатическая переменная… На нее нельзя ссылаться из статического контекста», можно сделать две вещи:
- Вы можете объявить переменные статическими.
- Вы можете создавать экземпляры нестатических объектов в статических методах.
Пожалуйста, прочтите это руководство:Разница между статическими и нестатическими переменными。
19. “Non-Static Method … Cannot Be Referenced From a Static Context”
Эта проблема возникает, когда код Java пытается вызвать нестатический метод в статическом классе. Например, такой код:
class Sample
{
private int age;
public void setAge(int a)
{
age=a;
}
public int getAge()
{
return age;
}
public static void main(String args[])
{
System.out.println("Age is:"+ getAge());
}
}
Вызовет эту ошибку:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method getAge() from the type Sample
Чтобы вызвать нестатический метод в статическом методе, необходимо объявить экземпляр класса вызываемого нестатического метода.
Прочтите эту статью:Разница между нестатическими и статическими методами。
20. “(array) Not Initialized”
Если массив был объявлен, но не инициализирован, вы получите сообщение об ошибке типа «(массив) не инициализирован». Длина массива фиксирована, поэтому каждый массив необходимо инициализировать требуемой длиной.
Следующий код правильный:
AClass[] array = {object1, object2}
это тоже нормально:
AClass[] array = new AClass[2];
...
array[0] = object1;
array[1] = object2;
Но это не так:
AClass[] array;
...
array = {object1, object2};
Прочтите эту статью:О том, как инициализировать массив в Java。
Продолжение следует
Сегодня мы обсуждали ошибки компилятора, в следующий раз мы обсудим различные исключения времени выполнения, которые могут возникнуть. Как и структура этой статьи, в следующий раз она будет содержать фрагменты кода, пояснения и ссылки по теме, которые помогут вам исправить код как можно скорее.
И так, код с учебника, но и в этом коде умудрился допустить ошибку. Уже замахался искать, вобщем ступор. Помогите! Заранее спасибо.
Вот код:
| Java | ||
|
Вот ошибка:
Exception in thread «main» java.lang.RuntimeException: Uncompilable source code — Erroneous tree type: <any>
at mynotebook.MyNotebook.<init>(MyNotebook.java:33)
at mynotebook.MyNotebook.main(MyNotebook.java:45)
Java Result: 1
Из-за чего ошибка появилась. Вроде все верно.
I am getting an error at public Rectangle(double width, double height){ saying that it’s an invalid method declaration, return type required. I’m not sure how to fix it. These are also my instructions for my assignment:
Write a super class encapsulating a rectangle. A rectangle has two attributes representing the width and the height of the rectangle. It has methods returning the perimeter and the area of the rectangle. This class has a subclass, encapsulating a parallelepiped, or box. A parallelepiped has a rectangle as its base, and another attribute, its length. It has two methods that calculate and return its area and volume.
`public class Rectangle1
{
private double width;
private double height;
public Rectangle1(){
}
public Rectangle(double width, double height){
this.width = width;
this.height = height;
}
public double getWidth(){
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public double getArea(){
return width * height;
}
public double getPerimeter(){
return 2 * (width + height);
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle1 rectangle = new Rectangle1(2,4);
System.out.println("nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter());
}
}`
asked Nov 20, 2012 at 22:55
3
Constructor name should be same as your class name. your class name is Rectangle1 thus your Constructor name should be the same as well, currently java compiler this it as an method without a return type, thus it complains.
public Rectangle(double width, double height){
should be
public Rectangle1(double width, double height){
answered Nov 20, 2012 at 22:55
![]()
PermGenErrorPermGenError
45.7k8 gold badges86 silver badges106 bronze badges
6
I am getting an error at public Rectangle(double width, double height){ saying that it’s an invalid method declaration, return type required. I’m not sure how to fix it. These are also my instructions for my assignment:
Write a super class encapsulating a rectangle. A rectangle has two attributes representing the width and the height of the rectangle. It has methods returning the perimeter and the area of the rectangle. This class has a subclass, encapsulating a parallelepiped, or box. A parallelepiped has a rectangle as its base, and another attribute, its length. It has two methods that calculate and return its area and volume.
`public class Rectangle1
{
private double width;
private double height;
public Rectangle1(){
}
public Rectangle(double width, double height){
this.width = width;
this.height = height;
}
public double getWidth(){
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){
this.height = height;
}
public double getArea(){
return width * height;
}
public double getPerimeter(){
return 2 * (width + height);
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle1 rectangle = new Rectangle1(2,4);
System.out.println("nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter());
}
}`
asked Nov 20, 2012 at 22:55
3
Constructor name should be same as your class name. your class name is Rectangle1 thus your Constructor name should be the same as well, currently java compiler this it as an method without a return type, thus it complains.
public Rectangle(double width, double height){
should be
public Rectangle1(double width, double height){
answered Nov 20, 2012 at 22:55
![]()
PermGenErrorPermGenError
45.7k8 gold badges86 silver badges106 bronze badges
6