Я все время получаю «ошибка: не удается найти символ» при попытке создать цепочку конструктора - PullRequest
1 голос
/ 20 июня 2020

Итак, это часть моего кода, содержащая конструкторы. Как видите, цель состоит в том, чтобы конструкторы принимали меньше параметров и вызывали наиболее точные c конструкторы. Я думал, что инициировал свои значения в первом конструкторе. Почему он не может найти мой символ?

Вот мой код:

 public class Frog{

// instance variables 
 private String name;
 private int  age;
 private double tongueSpeed;
 private boolean isFrogLet;
 private  String species;

**// Third constructor** 
public Frog( String Name){
 this(Name, Age, TongueSpeed, IsFrogLet, Species);
 
 }


**//second constructor** 
 public Frog(String Name, int ageInYears, double TongueSpeed){
   this(Name, Age, TongueSpeed, IsFrogLet, Species);
   name= Name;
   age = ageInYears;
   tongueSpeed= TongueSpeed;
 }

**// most specific constructor**
 public Frog( String Name, int age, double TongueSpeed, boolean IsFrogLet, String Species){
   name = Name;
   this.age = Age;
   tongueSpeed = TongueSpeed;
   isFrogLet= IsFrogLet;
   species = Species;
 }

public void grow(int months){
 age = age + months;
 while ( age < 12){
  tongueSpeed++;
 }
 if (age>5 & age>30){
  double highRes= age-30;
  tongueSpeed= tongueSpeed-highRes;
 }
 if (age>1 & age <7){
  isFrogLet = true;
 }
}

}

-Это моя ошибка, которую я получаю:

Frog.java:12: error: cannot find symbol
 this(Name, Age, TongueSpeed, IsFrogLet, Species);
            ^
  symbol:   variable Age
  location: class Frog
Frog.java:12: error: cannot find symbol
 this(Name, Age, TongueSpeed, IsFrogLet, Species);
                 ^
  symbol:   variable TongueSpeed
  location: class Frog
Frog.java:12: error: cannot find symbol
 this(Name, Age, TongueSpeed, IsFrogLet, Species);
                              ^
  symbol:   variable IsFrogLet
  location: class Frog
Frog.java:12: error: cannot find symbol
 this(Name, Age, TongueSpeed, IsFrogLet, Species);
                                         ^
  symbol:   variable Species
  location: class Frog
Frog.java:19: error: cannot find symbol
   this(Name, Age, TongueSpeed, IsFrogLet, Species);
              ^
  symbol:   variable Age
  location: class Frog
Frog.java:19: error: cannot find symbol
   this(Name, Age, TongueSpeed, IsFrogLet, Species);
                                ^
  symbol:   variable IsFrogLet
  location: class Frog
Frog.java:19: error: cannot find symbol
   this(Name, Age, TongueSpeed, IsFrogLet, Species);
                                           ^
  symbol:   variable Species
  location: class Frog
Frog.java:28: error: cannot find symbol
   this.age = Age;
              ^
  symbol:   variable Age
  location: class Frog

Ответы [ 3 ]

3 голосов
/ 20 июня 2020

Я думаю, вы неправильно понимаете концепцию перегрузки конструктора. **// Third constructor** принимает только имя, но вы все еще пытаетесь передать this другие данные. Вы не можете передать материал, если его не существует. Так что передайте то, что исходит из параметров, и установите другие значения в null следующим образом:

public Frog( String Name){
   this(Name, 0, 0.0, false, null));
}

То же самое относится и к другим конструкторам. Посмотрите, каковы параметры конкретных конструкторов, и установите другие параметры null.

1 голос
/ 20 июня 2020

ошибка не требует пояснений. Вы не создаете переменные с указанными именами c во втором и третьем конструкторах перед их передачей наиболее конкретному конструктору c. Вы должны либо передать точную переменную, которую вы получаете в своем конструкторе, в базовый конструктор, либо вы должны передать некоторые значения по умолчанию в наиболее специфичный конструктор c вместо этих переменных (также известных как символы). поэтому вы должны вызывать свои второй и третий конструкторы следующими способами:

// Third constructor
public Frog(String Name) {
    this(Name, 0, 0.0, false, "");
}


//second constructor
public Frog(String Name, int ageInYears, double TongueSpeed) {
    this(Name, ageInYears, TongueSpeed, false, "");
}  

Надеюсь, это поможет

0 голосов
/ 21 июня 2020

Причина ошибки

Вы используете несуществующие переменные, поскольку ваш уровень экземпляра находится в camelCase нет в заголовке Переменные случая, отличные от этого, найдите отредактированный код и попробуйте использовать camelCase для переменной

public class Frog {
    private String name;
    private int age;
    private double tongueSpeed;
    private boolean isFrogLet;
    private String species;

    public Frog(String name, int age, double tongueSpeed, boolean isFrogLet, String species) {
        this.name = name;
        this.age = age;
        this.tongueSpeed = tongueSpeed;
        this.isFrogLet = isFrogLet;
        this.species = species;
    }

    public Frog(String name) {
        this.name = name;
    }

    public Frog(String name, int ageInYears, double TongueSpeed) {
        this.name = name;
        this.age = ageInYears;
        this.tongueSpeed = TongueSpeed;
    }

    public void grow(int months) {
        age = age + months;
        while (age < 12) {
            tongueSpeed++;
        }
        if (age > 5 & age > 30) {
            double highRes = age - 30;
            tongueSpeed = tongueSpeed - highRes;
        }
        if (age > 1 & age < 7) {
            isFrogLet = true;
        }
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...