Java class "cannot be resolved to a type" - java

This is the error I'm getting:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
TeamLeader cannot be resolved to a type
at TeamLeadDemo.main(TeamLeadDemo.java:26)
This is my code:
import java.util.Scanner;
public class Employee {
public String empName, empNumber, hireDate;
public class TeamLeadDemo {}
public Employee(String empName, String empNumber, String hireDate) {
this.setEmpName(empName);
this.setEmpNumber(empNumber);
this.setHireDate(hireDate);
}
public void setEmpName(String empName) {
this.empName = empName;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public void setHireDate(String hireDate) {
this.hireDate = hireDate;
}
public String getEmpName() {
return empName;
}
public String getEmpNumber() {
return empNumber;
}
public String getHireDate() {
return hireDate;
}
public class ShiftSupervisor extends Employee {
public double annualSalary, annualProduction;
//constructor
public ShiftSupervisor(String empName, String empNumber,
String hireDate, double annualSalary,
double annualProduction) {
super(empName,empNumber, hireDate);
this.setAnnualSalary(annualSalary);
this.setAnnualProduction(annualProduction);
}
public double getAnnualSalary() {
return annualSalary;
}
public double getAnnualProduction() {
return annualProduction;
}
public void setAnnualSalary(double annualSalary) {
this.annualSalary = annualSalary;
}
public void setAnnualProduction(double annualProduction) {
this.annualProduction = annualProduction;
}
public String toString() {
return "Name: "+ getEmpName() + "\nEmpID: "+ getEmpNumber()
+ "\nHire Date: "+ getHireDate() + "\nAnnual Salary: "
+ annualSalary + "\nProduction: "+ annualProduction;
}
public class employeeStart {
public void main(String[] args) {
String name, id, date;
double sal, prod;
//create scanner object
Scanner keyboard = new Scanner(System.in);
//inputting data
System.out.println("Enter Name: ");
name = keyboard.nextLine();
System.out.println("Enter id: ");
id = keyboard.nextLine();
System.out.println("Enter Hire Date: ");
date = keyboard.nextLine();
System.out.println("Enter Annual: ");
sal = keyboard.nextDouble();
System.out.println("Enter production: ");
prod = keyboard.nextDouble();
//instantiating object
ShiftSupervisor pw = new ShiftSupervisor(name, id, date, sal, prod);
//outputting data
System.out.println("Employee Details: \n" + pw);
}
}
public class TeamLeader {
public double monthlyBonus;
public int minTraining, trainingPresent;
public TeamLeader(double monthlyBonus, int minTraining, int trainingPresent) {
this.setMonthlyBonus(monthlyBonus);
this.setMinTraining(minTraining);
this.addtrainingPresent(trainingPresent);
}
public void setMonthlyBonus(double monthlyBonus) {
this.monthlyBonus = monthlyBonus;
}
public void setMinTraining(int minTraining) {
this.minTraining = minTraining;
}
public void setTrainingPresent(int t) {
trainingPresent = t;
}
public void addtrainingPresent(int hours) {
trainingPresent += hours;
}
public double getMonthlyBonus() {
return monthlyBonus;
}
public int getMinTraining() {
return minTraining;
}
public int getTrainingPresent() {
return trainingPresent;
}
public String toString() {
return "Bonus: "+ getMonthlyBonus() + "\nMinimum Training: "
+ getMinTraining() + "\nAttendence: "+ getTrainingPresent();
}
}
}
}
In addition, I declared this in a separate class:
import java.util.Scanner;
public class TeamLeadDemo extends Employee {
public TeamLeadDemo(String empName, String empNumber, String hireDate) {
super(empName, empNumber, hireDate);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
double sal;
int min, atten;
//create scanner object
Scanner keyboard = new Scanner(System.in);
//inputting data
System.out.println("Enter minimum training: ");
min = keyboard.nextInt();
System.out.println("Enter id: ");
atten = keyboard.nextInt();
System.out.println("Enter Bonus: ");
sal = keyboard.nextDouble();
//instantiating object
ShiftSupervisor pw = new TeamLeader(sal, min, atten);
//outputting data
System.out.println("Employee Details:\n" + pw);
}
}
What is causing this error and how might I resolve it?
EDIT: Indentation, whitespace, naming conventions and readability issues have been somewhat addressed.

If this problem is with maven project then right-click Maven > Update Project should solve the problem

The problem is that TeamLeader appears to be an inner class (hard to tell, your indentation is bad), and since it's not static, you can't instantiate it by itself.
You either need to make TeamLeader its own class, or make it a static class and instantiate it as Employee.TeamLeader (or whatever the parent class is, your indentation is really not helpful here).

Your exception message says this
Exception in thread "main" java.lang.Error: Unresolved compilation problem: TeamLeader cannot be resolved to a type
This means that you have tried to run a program that used some class that has not compiled correctly.
Go back and fix the compilation error(s).
It is not clear what the fix for the compilation error should be, but the error is saying that it cannot find a class called TeamLeader. Perhaps it doesn't exist. Perhaps it is in a different package. Perhaps you haven't compiled it. Perhaps something else.
Looking at the code, I think the problem is that you have defined two distinct classes called TeamLeadDemo, one as a nested class of Employee and the second as a top-level class. Furthermore the second of these is attempting to use TeamLeader ... but the TeamLeader class that you have actually declared is nested 2 levels down in Employee; i.e. its real name is Employee.ShiftSupervisor.TeamLeader.
This is all a bit nonsensical.
By the look of it, you defined a whole bunch of classes in the same file ("Employee.java") without much understanding of what it means to put one class inside another. Most likely, each of those classes should be declared in its own file. And most likely you should just delete the nested TeamLeadDemo class.

That error can appear also if you create the inner class by moving it from somewhere, and with reorganization, you put the import line for that inner class in its outer class file. After that the inner class cannot be resolved to a type anywhere. Automatic insert of import won't help.
You have not published the import section of the outer class and we cannot check that variant. Check for it, and if the excessive import is there, remove it.
And if you work in Eclipse, it is very probable you need to clean the project after that.

Related

Inherited objects outputs as null

I have Employee as my main class (used to get the name and call other methods). I created two inheritance class called FullTimeEmployee and PartTimeEmployee. The program is working except the getName() in my subclasses. The name the I input works in the main class but shows up as null in the subclasses. It always outputs null and I don't know what is wrong. Can you tell me what's wrong and appreciate the help to fix it?
Main Class
import java.util.Scanner;
public class Employee {
String name;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Employee emp = new Employee();
FullTimeEmployee fte = new FullTimeEmployee();
PartTimeEmployee pte = new PartTimeEmployee();
System.out.println("Please input your name: ");
String Empname = input.nextLine();
emp.setName(Empname);
System.out.println(emp.getName());
System.out.println("Press F for Full Time or P for Part Time: ");
char pftype = input.next().charAt(0);
switch (pftype) {
case 'P','p':
pte.PartTimeEmployee();
break;
case 'F', 'f':
fte.FullTimeEmployee();
break;
default :
System.out.println("Invalid Output");
break;
}
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Sub classes
import java.util.Scanner;
public class FullTimeEmployee extends Employee{
double monthlySalary;
String name;
public void FullTimeEmployee() {
FullTimeEmployee fte = new FullTimeEmployee();
fte.writeOutput();
System.out.println("______________________________________");
System.out.println("Employee name: "+ fte.getName());
System.out.println("Monthly Salary: "+ fte.getMonthlysalary());
}
public void writeOutput() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your monthly salary: ");
double FEsalary = input.nextDouble();
setMonthlySalary(FEsalary);
}
public void setMonthlySalary(double monthlySalary){
this.monthlySalary = monthlySalary;
}
public double getMonthlysalary(){
return monthlySalary;
}
}
import java.util.Scanner;
public class PartTimeEmployee extends Employee {
double ratePerHour, wage;
int hoursWorked;
String name;
public void PartTimeEmployee() {
PartTimeEmployee pte = new PartTimeEmployee();
String name = pte.getName();
pte.readInput();
System.out.println("______________________________________");
System.out.println("Employee name: "+ pte.getName());
System.out.println("Monthly Salary: "+ pte.getWage());
}
public void readInput(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your rate per hour and number of hours worked seperated by a space: ");
String[] salary = input.nextLine().split(" "); //SCAN THE INPUT OF THE USER AND STORE THEM IN AN ARRAY. SPLITS THE WHITE SPACE.
try { //TRY THE CODE AND BE TESTED FOR ERRORS BEFORE BEING EXECUTED
ratePerHour = Double.parseDouble(salary[0]);
hoursWorked = Integer.parseInt(salary[1]);
setWage(ratePerHour, hoursWorked);
} catch (Exception e) { // CATCH THE STATEMENT IF AN ERROR OCCURED ON THE CODE
System.out.println("Invalid input");
System.exit(0);
}
}
public void setWage(double ratePerHour, int hoursWorked){
wage = ratePerHour * hoursWorked;
}
public double getWage(){
return wage;
}
}
OUTPUT OF EITHER
Employee name: null
Monthly Salary: 1110.0
I'm pretty new at coding and just started learning so please excuse if my code is very redundant or has errors. Appreciate the help!
You are not setting the empName anywhere to your inherited class objects i.e. FullTimeEmployee and PartTimeEmployee.
You are setting empName to only employee object.
emp.setName(Empname);
There are 3 different kind of objects here Employee(), PartTimeEmployee(), and FullTimeEmployee(). You are setting name only on Employee object. One way to do it is omit the re-declaration of name in your derived classes.
String name; //delete this from your derived classes
And just use the name of your parent class.
i.e.
System.out.println("Employee name: "+ getName()); // just getName() from base class
System.out.println("Monthly Salary: "+ pte.getWage());
Your derived classes have their own names, separate from the base class' name.
When you assign this.name you initialize the 'local' class member and the parent class' name remains null.

Main objectives of java Runtime Exception and why they occur as well as the best practices for evasion of java runtime exception

Hello fellow pragmatic programmers, I have this program which I developed which is a social network program written in java and the main functions of this program is to allow the user to: add a friend, delete friend, see who has the most friends, see who has the most high influence and the ability to exit out of the program.
As with any programs there will be a blip or two, for me it is a case of the java runtime exception this keeps of propping up after I tried to remedy the problem by seeing if it will work without the main package or if I tried to change the way I have written the program to no avail.
This is the error message that keeps on propping up:
Select:
[1] Add Friend
[2] Delete Friend
[3] List Friends
[4] Friends of Friends
[5] Most Popular
[6] Most Influencer
[7] Exit
7
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: uelbook.Person
at uelbook.UELbook.main(UELbook.java:20)
Line 20 of my main class which is UELbook which is down below is:
Person listfriends=new Person();
UELbook:
package uelbook;
import java.util.*;
import java.io.*;
public class UELbook {
public static void main(String[] args) {
UELbook uelbook = new UELbook();
//test your code here
Scanner scanner=new Scanner(System.in);
System.out.println("Select:");
System.out.println("[1] Add Friend");
System.out.println("[2] Delete Friend");
System.out.println("[3] List Friends");
System.out.println("[4] Friends of Friends");
System.out.println("[5] Most Popular");
System.out.println("[6] Most Influencer");
System.out.println("[7] Exit");
int choice=scanner.nextInt();
Person listfriends=new Person();
while(choice!=7){
int num=0;
//ADD
if(choice==1){
System.out.println("ID: ");
String id=scanner.nextLine();
System.out.println("Username: ");
String username=scanner.nextLine();
System.out.println("Password: ");
String password=scanner.nextLine();
listfriends.set(id, username, password);
listfriends.addFriend();
}
//DELETE
if(choice==2){
System.out.println("ID: ");
String id=scanner.nextLine();
System.out.println("Username: ");
String username=scanner.nextLine();
System.out.println("Password: ");
String password=scanner.nextLine();
listfriends.set(id, username, password);
listfriends.removeFriend();
}
//LIST
if(choice==3){
for(int i=0;i<1;i++){
System.out.println(listfriends.list);
}
}
System.out.println("ID: ");
String id=scanner.nextLine();
System.out.println("Username: ");
String username=scanner.nextLine();
System.out.println("Password: ");
String password=scanner.nextLine();
//REMOVE
if(choice==7){
System.exit(0);
}
if(choice==8){
System.out.println("ERROR! Please choose from the options.");
}
}//WHILE LOOP EXIT
}
public void addPerson(String id, String firstname, String lastname) throws PersonExistsException {
//list.add(ID);
// list.add(firstname);
//list.add(lastname);
}
public String getPerson(String id) throws NoSuchCodeException {
return id;
}
public void addFriendship(String id1, String id2) throws NoSuchCodeException {
id1=id1;
id2=id2;
}
public Collection<String> listFriends(String id) throws NoSuchCodeException {
return null;
}
public Collection<String> friendsOfFriends(String id) throws NoSuchCodeException {
return null;
}
//The methods returns true if the file has been loaded,
//false in case of any errors
public boolean loadFile(String file) {
return false; // remove this in the implementation
}
//The methods returns true if the file has been saved,
//false in case of any errors
public boolean saveFile(String file) {
return false; // remove this in the implementation
}
public String mostPopular() {
return null; // remove this in the implementation
}
public String mostInfluencer() {
return null; // remove this in the implementation
}
}
Person:
package UELbook;
import java.util.*;
import java.io.*;
public class Person {
String ID;
String firstname;
String lastname;
ArrayList<String>list=new ArrayList<String>();
public static void main(String[]args){
}
//CONSTRUCTOR
public void set(String ID, String firstname, String lastname){
setID(ID);
setFirstName(firstname);
setLastName(lastname);
}
//SETTERS
public void setID(String ID){
ID=ID;
}
public void setFirstName(String FirstName){
firstname=FirstName;
}
public void setLastName(String LastName){
lastname=LastName;
}
//GETTERS
public String getID(){
return ID;
}
public String getFirstName(){
return firstname;
}
public String getLastName(){
return lastname;
}
public void addPerson(String id, String firstname, String lastname) throws uelbook.PersonExistsException {
list.add(ID);
list.add(firstname);
list.add(lastname);
}
}
Person Exists Exception:
package uelbook;
#SuppressWarnings("serial")
public class PersonExistsException extends Exception {
}
No Such Code Exception:
package uelbook;
#SuppressWarnings("serial")
public class NoSuchCodeException extends Exception {
}
Any helpful hints will be much appreciated.
Your Person class is using package UELbook.
Presumably that should be uelbook.
(Updated to provide an explanation....)
It is only a convention (though followed 99.99% of the time) that the package name should be in all lower case. Oracle states the following as the reason for this:
Package names are written in all lower case to avoid conflict with the
names of classes or interfaces.
In the code in the OP there is:
A package named UELbook
Another package named uelbook
A class named UELbook
So you are getting a clash between class UELbook and package UELbook. Changing the package name UELbook to uelbook should fix your problem from a technical perspective. However, as a related issue, after that you should change the name of your package uelbook or your class UELbook to remove all ambiguity.

Can not find symbol, unknown Identifier. How can I finish this?

Trying to get my Inheritance homework done and I have soo many error i am not sure where to start.
I am to create a Class called Horse that has a name, color and Date of Birth feild; with set and get methods. Then a subclass that is Race horse that adds number of races the horse has be in; also with Get and set method. Last an app that demos the using of each objects of each class. I am soo confused that i am unsure what I have even done.
I have a start
package horse;
public class Horse
{
//Horse has 3 fields
private String name;
private String color;
private int dob;
public String setName()
{
return name;
}
public void setName(String nName)
{
name = nName;
}
public String setColor()
{
return color;
}
public void setColor(String nColor)
{
color = nColor;
}
public int setdob()
{
return dob;
}
public void setName(int nDob)
{
dob = nDob;
}
}
With done I made this
package horse;
import java.util.*;
public class Horse2
{
String name;
String color;
int dob;
Horse aName = new Horse();
Horse aColor = new Horse();
Horse aDob = new Horse();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of horse");
name = keyboard.next();
aName.setName(name);
System.out.println("Enter color of horse");
color = keyboard.next();
aColor.setColor(color);
System.out.println("Please enter Date of Birth");
dob - keyboard.next();
aDob.setdob(dob);
}
This is new error
Exception in thread "main" java.lang.UnsupportedOperationException: Not supported yet.
at horse.Horse.setdob(Horse.java:43)
at horse.Horse2.main(Horse2.java:30)
C:\Users\Matthew\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 9 seconds)
The structure of a class is as follows
public class Xxx {
// <Field, Method, Constructor, Inner Class and Initializer Declarations>
int n; // Field declaration of n.
public static void main(String[] args) { // Method declaration of main.
// <Statements>
System.out.println("Hello");
}
}
You placed the System.out.println call immediately under the top level braces, where a declaration is expected.

"error: cannot find symbol" regarding on Inheritance-related program

I got a message says error: cannot find symbol regarding on c1.certificateAwarded(grade); statement. I have no idea what is the problem. Really need all the help I can get.
Here's the code:
ExamDetails.java
package Exams;
import javax.swing.JOptionPane;
public class ExamDetails {
public static void main(String[] args) {
StudentResults sr = new StudentResults();
sr.inputStudentName();
sr.inputExamName();
sr.inputScore();
sr.inputGrade();
sr.DisplayDetails();
Certificates c1 = new Certificates();
c1.certificateAwarded(grade);
}
}
StudentResults.java
package Exams;
import javax.swing.JOptionPane;
public class StudentResults {
private String fullname;
private String examName;
private int examScore;
private int examGrade;
public String getStudentName()
{
return fullname;
}
public void setStudentName(String name)
{
fullname = name;
}
public String getExamName()
{
return examName;
}
public void setExamName(String exam)
{
examName = exam;
}
public int getExamScore()
{
return examScore;
}
public void setExamScore(int score)
{
examScore = score;
}
public int getExamGrade()
{
return examGrade;
}
public void setExamGrade(int grade)
{
examGrade = grade;
}
public void inputStudentName()
{
fullname = JOptionPane.showInputDialog("Enter the student's name");
}
public void inputExamName()
{
examName = JOptionPane.showInputDialog("Enter the subject's name");
}
public void inputScore()
{
String scoreString = new String();
JOptionPane.showInputDialog("Enter the student's score");
examScore = Integer.parseInt(scoreString);
}
public void inputGrade()
{
String gradeString = new String();
JOptionPane.showInputDialog("Enter the student's grade");
examGrade = Integer.parseInt(gradeString);
}
public String DisplayDetails()
{
String d;
d = "Student Name : " + fullname + "Exam Name : " + examName + "Score : " + examScore + "Grade : " + examGrade;
return d;
}
}
Certificates.java
package Exams;
public class Certificates extends StudentResults {
private String certificate;
public String Grade;
Certificates()
{
super();
certificate = "No Certificate Awarded";
}
String certificateAwarded(/*int grade*/) {
//StudentResults g = new StudentResults();
//Grade = g.inputGrade();
//Grade = inputGrade(examGrade);
if(Grade.equals("Grade : A"))
{
this.certificate = "Certificate of Excellence";
}
else
if(Grade.equals("Grade : B"))
{
this.certificate = "Certificate of Achievement";
}
else
if(Grade.equals("Grade : C"))
{
this.certificate = "Certificate of Achievement";
}
else
this.certificate = "No Certificate Awardedt";
return this.certificate;
}
}
In the ExamDetails.java class, you don't declare or instantiate the grade variable that you're passing to the certificateAwarded method.
Also, you have parameters commented out in your Certificates.java class. You should uncomment the parameter.
For your code to compile, grade would have to be either
a local variable declared within the main method
a field defined on the ExamDetails class
Neither of these declarations are present so the compiler is telling you that it can't find the grade "symbol".
Try adding int grade = sr.getExamGrade(); above the problem line, or something similar.
As the comment suggested, you need to have "grade" declared. Without it, the compiler can't complete determining what the signature is for Certficates.certificateAwarded, since what goes in the argument list is part of the signature. More importantly, you have this in your code:
String certificateAwarded(/* int grade */)
The parameter, "int grade" is commented out. So the compiler sees this:
String certificateAwarded( )
So, what the compiler might be telling you is that it is looking for a method of Certificates named certificateAwarded that takes 1 argument of type {whatever type "grade" is}. It doesn't find that.
I said "might be" because you are missing two symbols on the line in question: grade and a method with a matching signature.
I can think of two things you can try to fix it:
Change " c1.certificateAwarded(grade);" to "c1.certificateAwarded();"
Declare "grade" to be an int somewhere in main (or in a place that is visible within main) and change "String certificateAwarded(/int grade/)" to "String certificateAwarded(int grade)".
I would start by trying the first option. If it is necessary to try the second, you will need to add additional code in both main (or place where grade is visible to main) and in the certificateAwarded method.

The constructor CompanyDetail() is undefined (java)

import java.io.*;
import java.util.*;
public class CompanyDetail {
int Id;
String name;
String department;
static String companyname="Maruti Suzuki";
CompanyDetail(int ID,String Name,String Dept) {
Id=ID;
name=Name;
department=Dept;
}
public void getdata() {
try {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
System.out.println("Employee Id :");
Id = Integer.parseInt(br.readLine());
System.out.println("Employee name :");
name= br.readLine();
System.out.println("Employee Department :");
department=br.readLine();
System.out.println("Company is :"+companyname);
}
catch(Exception e) {
}
}
public void printdata() {
System.out.println("Employee Id is :"+Id);
System.out.println("Employee Name is :"+name);
System.out.println("Employee Department is :"+department);
System.out.println("Company is :"+companyname);
}
}
public class CompanyUse {
public static void main(String[] args) {
CompanyDetail cd = new CompanyDetail(int Id,String name,String department);
cd.getdata();
cd.printdata();
}
}
i am getting error in a main block when i create a object..eclips keep teeling me that constructor CompanyDetail() is undefined....and without constructor it gives me a null value in my output..please help me ..i ve just started learning java...thank you very much in advance :)
Default constructor (with empty parameter list) is created automatically by the compiler only when you don't create any other constructor. In your case you have CompanyDetail(int ID,String Name,String Dept) so it wasn't automatically generated. You could write default constructor yourself:
CompanyDetail() {}
Also I have some tips:
this code isn't compiling, please fix all the errors - java compiler is quite good at saying what's wrong with code (:
never, ever use empty catch block,
try to follow naming conventions popular in Java.

Categories

Resources