Ошибка cannot be applied to given types

Добрый день, компилятор ругается на конструкторы книг Марка Твена и Агаты Кристи.
не могу понять где именно ошибка. Вот что выдаёт компилятор

constructor Book in class com.javarush.task.task15.task1504.Solution.Book
cannot be applied to given types; required: java.lang.String found: no arguments reason:
actual and formal argument lists differ in length:
Solution.java, line: 50, column: 43
cannot find symbol symbol: method Book(java.lang.String):
Solution.java, line: 51, column: 18
constructor Book in class com.javarush.task.task15.task1504.Solution.Book
cannot be applied to given types; required: java.lang.String found: no arguments reason:
actual and formal argument lists differ in length:
Solution.java, line: 65, column: 48
cannot find symbol symbol: method Book(java.lang.String):
Solution.java, line: 66, column: 18

а вот что у меня в коде

package com.javarush.task.task15.task1504;

import java.util.LinkedList;
import java.util.List;

/*
ООП - книги
*/

public class Solution {
    public static void main(String[] args) {
        List<Book> books = new LinkedList<Book>();
        books.add(new MarkTwainBook("Tom Sawyer"));
        books.add(new AgathaChristieBook("Hercule Poirot"));
        System.out.println(books);
    }

    abstract static class Book {
        private String author;

        public Book(String author) {
            this.author = author;
        }

        public abstract Book getBook();

        public abstract String getTitle();

        private String getOutputByBookType() {
            String agathaChristieOutput = author + ", " + getBook().getTitle() + " is a detective";
            String markTwainOutput = getBook().getTitle() + " book was written by " + author;
            if(this instanceof AgathaChristieBook)
            return agathaChristieOutput;
            if(this instanceof MarkTwainBook)
            return markTwainOutput;


            String output = "output";
            //Add your code here

            return output;
        }

        public String toString() {
            return getOutputByBookType();
        }
    }
    public static class MarkTwainBook extends Book{
        private String title;
       public  MarkTwainBook(String title){
            super.Book("Mark Twain");
            this.title = title;
        }
         public MarkTwainBook getBook(){
             return this;
         }

        public  String getTitle(){
            return this.title;
        }

    }
    public static class AgathaChristieBook extends Book{
        private String title;
        public AgathaChristieBook(String title){
            super.Book("Agatha Christie");
            this.title = title;
        }
         public AgathaChristieBook getBook(){
             return this;
         }

        public  String getTitle(){
            return this.title;
        }
    }
}

I just added the constructor Building and I thought everything would work fine, but I’m getting an error on line 43. When I create the object, Building b = new Building();, it says I need to have a double and int in the argument, so I did as it said, but I just keep getting more errors. What am I doing wrong?

// This program lets the user design the area and stories of a building multiple times
// Author: Noah Davidson
// Date: February 20, 2014

import java.util.*;

public class Building // Class begins
{
    static Scanner console = new Scanner(System.in);

    double area; // Attributes of a building
    int floors;

    public Building(double squarefootage, int stories)
    {
        area = squarefootage;
        floors = stories;
    }

    void get_squarefootage() // User enters the area of floor
    {
        System.out.println("Please enter the square footage of the floor.");
        area = console.nextDouble();
    }

    void get_stories() // The user enters the amount of floors in the building
    {
        System.out.println("Please enter the number of floors in the building.");
        floors = console.nextInt();
    }

    void get_info() // This function prints outs the variables of the building
    {
        System.out.println("The area is: " + area + " feet squared");
        System.out.println("The number of stories in the building: " + floors + " levels");
    }

    public static void main(String[] args) // Main starts
    {
        char ans; // Allows for char

        do{ // 'do/while' loop starts so user can reiterate
            // the program as many times as they desire

            Building b = new Building(); // Creates the object b
            b.get_squarefootage(); // Calls the user to enter the area
            b.get_stories(); // Calls the user to enter the floors
            System.out.println("---------------");
            b.get_info(); // Displays the variables
            System.out.println("Would you like to repeat this program? (Y/N)");
            ans = console.next().charAt(0); // The user enters either Y or y until
                                            // they wish to exit the program

        } while(ans == 'Y' || ans == 'y'); // Test of do/while loop
    }
}

Peter Mortensen's user avatar

asked Mar 11, 2014 at 23:40

NJD's user avatar

3

Your problem is this line here: Building b = new Building(); // Creates the object b

Your constructor is set up to take two arguments, a double and an int, but you pass neither.

Try something like this to remove the error:

double area = 0.0;
int floors = 0;
Building b = new Building(area, floors);

Perhaps a better idea would be to just have a constructor that took no parameters:

public Building() {
    this.area = 0.0;
    this.floors = 0;
}

After I apply these changes, the code compiles and runs… (see the picture below)

Confirmation that the program compiles and runs

Mark Rotteveel's user avatar

answered Mar 11, 2014 at 23:42

Josh Engelsma's user avatar

4

I have fixed and tested your code. It now runs. You need to add two arguments to the constructor (double and int).

import java.util.*;

public class Building // The class begins
{
    static Scanner console = new Scanner(System.in);

    double area; // Attributes of a building
    int floors;

    public Building (double squarefootage, int stories)
    {
        area = squarefootage;
        floors = stories;
    }

    void get_squarefootage() // The user enters the area of floor
    {
        System.out.println ("Please enter the square footage of the floor.");
        area = console.nextDouble();
    }

    void get_stories() // The user enters the amount of floors in the building
    {
        System.out.println ("Please enter the number of floors in the building.");
        floors = console.nextInt();
    }

    void get_info() // This function prints outs the vaibles of the building
    {
        System.out.println ("The area is: " + area + " feet squared");
        System.out.println ("The number of stroies in the building: " + floors + " levels");
    }

    public static void main(String[] args) // Main starts
    {
        char ans; // Allows for char

        do{ // 'do/while' loop starts so user can reiterate
            // the program as many times as they desire

            double a = 1;
            int c = 2;
            Building b = new Building(a, c); // Creates the object b
            b.get_squarefootage(); // Calls the user to enter the area
            b.get_stories(); // Calls the user to enter the floors
            System.out.println("---------------");
            b.get_info(); // Displays the variables
            System.out.println("Would you like to repeat this program? (Y/N)");
            ans = console.next().charAt(0); // The user enters either Y or y until
                                            // they wish to exit the program

        } while(ans == 'Y' || ans == 'y'); // Test of do/while loop
    }
}

Peter Mortensen's user avatar

answered Mar 11, 2014 at 23:50

Neptune's user avatar

NeptuneNeptune

6072 gold badges8 silver badges19 bronze badges

import java.util.Scanner;

public class Building // Class begins
{
    static Scanner console = new Scanner(System.in);

    double area; // Attributes of a building
    int floors;

    void get_squarefootage() // User enters the area of floor
    {
        System.out.println("Please enter the square footage of the floor.");
        this.area = console.nextDouble();
    }

    void get_stories() // The user enters the amount of floors in the building
    {
        System.out.println("Please enter the number of floors in the building.");
        this.floors = console.nextInt();
    }

    void get_info() // This function prints outs the variables of the building
    {
        System.out.println("The area is: " + area + " feet squared");
        System.out.println("The number of stories in the building: " + floors + " levels");
    }

    public static void main(String[] args) // Main starts
    {
        char ans; // Allows for char

        do{ // 'do/while' loop starts so user can reiterate
            // the program as many times as they desire

            Building b = new Building(); // Creates the object b
            b.get_squarefootage(); // Calls the user to enter the area
            b.get_stories(); // Calls the user to enter the floors
            System.out.println("---------------");
            b.get_info(); // Displays the variables
            System.out.println("Would you like to repeat this program? (Y/N)");
            ans = console.next().charAt(0); // The user enters either Y or y until
                                            // they wish to exit the program

        } while(ans == 'Y' || ans == 'y'); // Test of do/while loop
    }
}

answered Apr 26, 2022 at 14:18

AISAN's user avatar

AISANAISAN

11 silver badge5 bronze badges

1

When I ran the first maven install I got an error regarding this line in BookmarkRestController.java:

[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /Users/is5960/Code/tutorials/demo/src/main/java/com/example/demo/BookmarkRestController.java:[55,39] method findOne in interface org.springframework.data.repository.query.QueryByExampleExecutor<T> cannot be applied to given types;
  required: org.springframework.data.domain.Example<S>
  found: java.lang.Long
  reason: cannot infer type-variable(s) S
    (argument mismatch; java.lang.Long cannot be converted to org.springframework.data.domain.Example<S>)
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.538 s
[INFO] Finished at: 2018-04-20T14:51:10-05:00
[INFO] Final Memory: 32M/383M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project demo: Compilation failure
[ERROR] /Users/is5960/Code/tutorials/demo/src/main/java/com/example/demo/BookmarkRestController.java:[55,39] method findOne in interface org.springframework.data.repository.query.QueryByExampleExecutor<T> cannot be applied to given types;
[ERROR]   required: org.springframework.data.domain.Example<S>
[ERROR]   found: java.lang.Long
[ERROR]   reason: cannot infer type-variable(s) S
[ERROR]     (argument mismatch; java.lang.Long cannot be converted to org.springframework.data.domain.Example<S>)
[ERROR] 
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

After digging in a little, I found this Stack Overflow question that implies maybe the tutorial should use getOne or findOneByEmail. When I change the line of code I can compile fine:

I’m a total Java and Spring newbie, so maybe I’m totally off-the-mark. Just thought I’d share this issue in case someone else runs into it.

оригинал: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 должны быть объявлены до их использования. Эта ошибка возникает из-за того, что компилятор не понимает значения идентификатора при компиляции кода.

cannot-find-symbol-error-screenshot-11495

Сообщение об ошибке «Не удается найти символ» может иметь множество причин:

  • Написание объявления идентификатора может не соответствовать написанию, используемому в коде.
  • Переменная никогда не объявлялась.
  • Переменная не объявлена ​​в той же области видимости.
  • Никакие классы не импортируются.

Прочтите эту статью:Обсуждение ошибки «не удается найти символ»。

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”

Когда информация, присвоенная переменной, превышает верхний предел, который может нести переменная, выдается ошибка «Возможная потеря точности». Как только это произойдет, часть информации будет отброшена. Если это не проблема, переменную следует явно объявить в коде как новый тип.

possible-loss-of-precision-error-11501

Ошибка «возможная потеря точности» обычно возникает в следующих ситуациях:

  • Попробуйте присвоить переменной целочисленного типа действительное число.
  • Попробуйте присвоить данные типа 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。

Продолжение следует

Сегодня мы обсуждали ошибки компилятора, в следующий раз мы обсудим различные исключения времени выполнения, которые могут возникнуть. Как и структура этой статьи, в следующий раз она будет содержать фрагменты кода, пояснения и ссылки по теме, которые помогут вам исправить код как можно скорее.

Solution 1:[1]

Since your super class Person doesn’t have a default constructor, in your sub classes (Student and Staff), you must call the super class constructor as the first statement.

You should define your sub class constructors like this:

Student() {
    super("a_string_value", an_int_value);// You have to pass String and int values to super class
}

Staff() {
    super("a_string_value", an_int_value); // You have to pass String and int values to super class
}

Solution 2:[2]

the first thing a constructor will do, is call the constructor (with same arguments) of the super class.
Person does not have a no-argument constructor, so, you must change your code in one of next two ways:

Student(String name, int yearOfBirth)
{
 //task.
}

or

Student()
{
super("", 0);
 //task.
}

and the same goes for Staff

Solution 3:[3]

Add super(NAME_IN_STRING_TYPE,YEAR_OF_BIRTH_IN_INT_TYPE); as a first statement in your subclasse’s constructor like

Student constructor

Student()
{
super("name", 1970); // String,int arguments passed
 //task.
}

Staff constructor

Staff()
{
super("name", 1970); // String,int arguments passed
 //task.
}

This is needed since there is no default no-arg constructor in the base class. You have to explicitly define a no-arg constructor in base class or you need to instruct the compiler to call the custom constructor of the base class.

Note : Compiler will not add default no-arg constructor in a class if it has a user defined constructor. It will add the default no-arg constructor only when there is no constructor defined in the class.

Solution 4:[4]

Try this:

Student(String name, int yearOfBirth) {
   super(name, yearOfBirth);
   // task...
}

Reason: you dont have a default constructor at your superclass. So you have to call super() at the first position in your subclass constructor.

Solution 5:[5]

To construct instance of Student you need to do actions neccesary to construct Person first. There is only one way to construct Person — two-arg constructor. That means you have to change Student like:

public Student() {
    super("someName", 1950); //first values came to my mind
}

Although you should be aware that Student should behave exactly like Person if treated as Person, i.e. have age and name. So actually I’d recommend to change Student constructor to include name and age there.

Solution 6:[6]

for constructor no param you should have two constructors like

public class Student {
Student(String name , int dateOfBirth)
{
 super(name,dateOfBirth)
}

Student()
{
 //task.
}

}

also same for other class

Solution 7:[7]

If you want to create an object of child class (ie Staff and Student) without passing parameters then you can create an additional constructor without parameters in the parent class (ie Person class) as below.

public class Person
{

   private String name;
   private int yearOfBirth;

   /**
    * Create a person with given name and age.
    */
   Person(String name, int yearOfBirth)
   {
      this.name = name;
      this.yearOfBirth = yearOfBirth;
   }
   
   // additional constructor without parameter
   Person(){
      // add your code here
   }
}

now below code will work without any error.

Staff stf = new Staff();
Student std = new Student();

Solution 8:[8]

student should not extend person.
bcoz, if we create obj for student, person’s constructor will be called automatically.

Понравилась статья? Поделить с друзьями:
  • Ошибка can шины форд фокус 2 рестайлинг
  • Ошибка cannot find module node js
  • Ошибка can шины форд мондео 4
  • Ошибка cannot find implementation of method
  • Ошибка can шины рендж ровер