I was given an empty class and instructed to fill it with instance variables and methods with bodies, which set or get values from the instance variables. Then I am to open another java file where code creating a new Contact object was provided and instructed to add additional code that uses that object to test all the methods created in the Contact class.
I am using the program Eclipse for coding/testing. The only things are correct are my method headers. When testing with what I have written (below) I get a null, null response (that is when I remove what wrote about the setPhoneNumber. When it's included I get a worse looking error
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: phoneNumber cannot be resolved to a variable.)
Any assistance on getting the get/set methods to work will be much appreciated. I am entirely new to any programming and have looked at about dozens of examples and have tried many variations with no success.
public class Contact
{
//Instance Variables
private String firstName;
private String lastName;
private int phoneNumber;
public String getFirstName() //method to retrieve first name
{
return this.firstName;
}
public void setFirstName(String firstName) //method to set the first name
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public int getPhoneNumber()
{
return this.phoneNumber;
}
public void setPhoneNumber(int phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public void call()
{
System.out.printf(getFirstName(), getLastName(), getPhoneNumber());
}
}
Here is the other java file used to test the Contact class above:
public class ContactTestDriver
{
public static void main(String[] args)
{
Contact contact = new Contact();
//all above was given; below are my code additions
String myContact;
myContact = contact.getFirstName();
contact.setFirstName();
System.out.println(myContact);
myContact = contact.getLastName();
contact.setLastName();
System.out.println(myContact);
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
System.out.println(myNumber);
}
}
After some helpful comments I have made changes but still no success. My error is "myContact cannot be resolved to a variable"
Here is the revised code:
public class Contact
{
//Instance Variables
private String firstName;
private String lastName;
private int phoneNumber;
public void setFirstName(String firstName) //method to set the first name
{
this.firstName = firstName;
}
public String getFirstName() //method to retrieve first name
{
return this.firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
public void setPhoneNumber(int phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public int getPhoneNumber()
{
return this.phoneNumber;
}
public void call()
{
System.out.printf("Who to call ", getFirstName(), getLastName(), getPhoneNumber());
}
}
And this is the code to test the Contact class:
public class ContactTestDriver
{
public static void main(String[] args)
{
Contact contact = new Contact();
//all above was given; below are my code additions
String firstName = "a"; //define first name
contact.setFirstName(firstName); //then set it
myContact = contact.getFirstName(); //then get it
System.out.println(myContact);
String lastName;
contact.setLastName(lastName);
myContact = contact.getLastName();
System.out.println(myContact);
int myNumber = 123;
contact.setPhoneNumber(phonNumber);
myNumber = contact.getPhoneNumer();
System.out.println(myNumber);
}
}
When you call contact.setFirstName(); which take String parameter you didn't pass the first name
public void setFirstName(String firstName){...}
and also with contact.setLastName(); : this also needs to send parameter
like this :
String lastName="//last name";
contact.setLastName(lastName);
and you need to know that we use the setter method before getter method
so first set the names then get it
String firstName = "a";////define the first name
contact.setFirstName(firstName); //// then set it
myContact = contact.getFirstName(); /// then get it
System.out.println(myContact);
String lastName = "b";
contact.setLastName(lastName);
myContact = contact.getLastName();
System.out.println(myContact);
int myNumber = 123;
contact.setPhoneNumber(myNumber);
myNumber = contact.getPhoneNumber();
System.out.println(myNumber);
This is what you have:
myContact = contact.getFirstName();
contact.setFirstName();
First you are getting, then you are setting. Reversing them makes more sense:
contact.setFirstName();
myContact = contact.getFirstName();
Moreover, set methods like setFirstName should receive a String parameter:
contact.setFirstName("Johny");
You can use Eclipse debugging tool.Run you java class in debug mode and add break points where ever you need to analyze data.
getter is just a method getting a field and setter is setting a new field.
you must set some values first i.e
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
System.out.println(myNumber);
int myNumber= "983445556"; // here you are creating an instance
or you can do it by
contact.setPhoneNumber(32435435345);
similarly for rest cases
Here phoneNumber is not a defined variable in your main method
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
it should be defined.
Related
I am attempting to update an Employee row in my Employee table using JDBI. However, the bindBean method doesn't appear to like my bean. I have included getters and setters. The bean has a public default constructor. The property names of the object are an exact match for the database column names. So the LastName String for instance, corresponds to a LastName database column. Exact match. What am I doing wrong here? Am I misconstruing how bindBean works? I also tried this same code with a prefix in front of the :parameters, still no dice.
EDIT: After a little more research, I believe the issue is coming from the fact that my column names and properties start with capital letters. Annotating my getters and setters with #ColumnName and the appropriate uppercase column names does not appear to be helping though.
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
Dao Method:
#Override
public void updateEmployee(Employee empl){
try(Handle handle = daoFactory.getDataSourceController().open()){
handle.createUpdate("UPDATE Employees SET LastName = :LastName, FirstName = :FirstName, EmailAddress = :EmailAddress, OnVacation = :OnVacation, Active = :Active, EscalationLevel = :EscalationLevel," +
" ScheduleExempt = :ScheduleExempt, GroupID = :GroupID, ScheduleID = :ScheduleID, SecurityGID = :SecurityGID, JobTitle = :JobTitle, Blurb = :Blurb WHERE IDX = :IDX")
.bindBean(empl)
.execute();
handle.commit();
}
catch(Exception e){
if(verbose){ e.printStackTrace(); }
logger.logError("Web-EmployeeDaoService-E04", "Error updating single user in DB.");
}
}
And my bean:
package app.pojos.Employee;
import java.io.Serializable;
import java.sql.Timestamp;
public class Employee implements Serializable {
private int IDX;
private String LastName;
private String FirstName;
private String EmailAddress;
private boolean OnVacation;
private boolean Active;
private int EscalationLevel;
private boolean ScheduleExempt;
private int GroupID;
private int ScheduleID;
private int SecurityGID;
private String JobTitle;
private String Blurb;
private Timestamp LastSeen;
private String ProfilePic;
//Default constructor
public Employee(){}
//Data mapped getters and setters
public int getIDX(){ return IDX; }
public void setIDX(int IDX){ this.IDX = IDX; }
public String getFirstName(){ return FirstName; }
public void setFirstName(String firstName){ this.FirstName = firstName; }
public String getLastName(){ return LastName; }
public void setLastName(String lastName){ this.LastName = lastName; }
public String getProfilePic(){ return ProfilePic; }
public void setProfilePic(String ProfilePic){ this.ProfilePic = ProfilePic; }
public String getEmailAddress(){ return EmailAddress; }
public void setEmailAddress(String emailAddress){ this.EmailAddress = emailAddress; }
public int getGroupID(){ return GroupID; }
public void setGroupID(int GroupID){ this.GroupID = GroupID; }
public boolean getScheduleExempt(){ return ScheduleExempt; }
public void setScheduleExempt(boolean ScheduleExempt){ this.ScheduleExempt = ScheduleExempt; }
public boolean getOnVacation(){ return OnVacation; }
public void setOnVacation(boolean OnVacation){ this.OnVacation = OnVacation; }
public boolean getActive(){ return Active; }
public void setActive(boolean Active){ this.Active = Active; }
public int getEscalationLevel(){ return EscalationLevel; }
public void setEscalationLevel(int EscalationLevel){ this.EscalationLevel = EscalationLevel; }
public int getScheduleID(){ return ScheduleID; }
public void setScheduleID(int ScheduleID){ this.ScheduleID = ScheduleID; }
public int getSecurityGID(){ return SecurityGID; }
public void setSecurityGID(int SecurityGID){ this.SecurityGID = SecurityGID; }
public String getJobTitle(){ return JobTitle; }
public void setJobTitle(String JobTitle){ this.JobTitle = JobTitle; }
public String getBlurb(){ return Blurb; }
public void setBlurb(String Blurb){ this.Blurb = Blurb; }
public Timestamp getLastSeen() { return LastSeen; }
public void setLastSeen(Timestamp LastSeen) { this.LastSeen = LastSeen; }
//Extra helper functions
public String getFullName(){ return this.FirstName + " " + this.LastName; }
}
SOLVED: Easy solution to this problem is to rename the named parameters in the query itself to match a lowercase version of the property names. i.e if the property is called Name, change the parameter in the query to :name and the problem is resolved without touching your beans or your database columns.
See this response for clarity. If you're like me and made the mistake of going against best practice naming conventions and capitalized all of your bean properties, this is an easy solution. You only need to change how you reference the properties in your create/update/insert queries and nothing else.
I have the following:
main.java
public class main {
public static void main(String[] args){
Player startingPitcher = new Player("Doug", "Mellon",
"Pitcher", 29);
startingPitcher.setThrowingArm("right");
}
}
Player.java
class Player
{
private String firstName, lastName, position;
private int age;
public Player(String firstName, String lastName, String position, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.age = age;
}
private String getFirstName(){
return this.firstName;
}
private void setFirstName(String newFirstName){
this.firstName = newFirstName;
}
private String getLastName(){
return this.lastName;
}
private void setLastName(String newLastName){
this.lastName = newLastName;
}
private String getPosition(){
return this.position;
}
private void setPosition(String newPosition){
this.position = newPosition;
}
private int getAge(){
return this.age;
}
private void setAge(int newAge){
this.age = newAge;
}
}
Pitcher.java
public class Pitcher extends Player{
public String throwingArm;
public int fastballMPH;
public Pitcher(String firstName, String lastName, String position, int age,
String throwingArm, int fastballMPH) {
super(firstName, lastName, position, age);
this.throwingArm = throwingArm;
this.fastballMPH = fastballMPH;
}
public String getThrowingArm(){
return this.throwingArm;
}
public void setThrowingArm(String newThrowingArm){
this.throwingArm = newThrowingArm;
}
private int getFastballMPH(){
return this.fastballMPH;
}
private void setFastballMPH(int newFastballMPH){
this.fastballMPH = newFastballMPH;
}
}
My main is throwing the following error:
Error:(6, 24) java: cannot find symbol symbol: method
setThrowingArm(java.lang.String) location: variable startingPitcher
of type Player
I understand the error - I think - but I thought you could access the methods if you were using inheritance.
How can I set the throwing arm for the Player object in my main?
Sorry if this question is worded poorly. If there is anything I can add to clarify my question, please don't hesitate to ask.
Thank you all very much for your time.
Variable startingPitcher in method main(), of class main, is an instance of Player and not an instance of Pitcher, hence it has no setThrowingArm() method.
You need to create an instance of Pitcher, i.e.
Pitcher startingPitcher = new Pitcher("Doug", "Mellon", "pitcher", 29, "right", 90);
Note that this is what the error message is telling you, namely that variable startingPitcher is an instance of Player (and not an instance of Pitcher).
We have an automation framework which uses excel sheet as test data.
To reduce test data file creation efforts i have used Java fake library to generate random data.My problem is,I have to pass these randomly generated test data to other test steps which compare these data with database.
Test Data files are having following fields:
1.First name
2.Last name
3.Address
4. orderid..etc
And these data is generated randomly and entering in website .
I tried to store all random data in text files.But i just want to avoid reading .txt file go through each line and the compare values with database.
Text File looks like-
Test case-1|Name-1|address-1|order Id-1
Test Case-2|Name-2|address-2|order-id-2
etc..
Is there any other way to store these values and compare with database?
Just create an bean as:
public class TestData {
public static String FirstName;
public static String lastName;
public static String Address;
public static String orderid;
public static String getFirstName() {
return FirstName;
}
public static void setFirstName(String firstName) {
FirstName = firstName;
}
public static String getLastName() {
return lastName;
}
public static void setLastName(String lastName) {
TestData.lastName = lastName;
}
public static String getAddress() {
return Address;
}
public static void setAddress(String address) {
Address = address;
}
public static String getOrderid() {
return orderid;
}
public static void setOrderid(String orderid) {
TestData.orderid = orderid;
}
}
You can use direct variable as I have put them public or getter/setter.
As the variable is static you call them directory with className
Example:
StepDefination1Class
TestData.setFirstName("Shubham");
OR
TestData.FirstName="Shubham";
Use the same varible in another class as below:
StepDefination2Class
String Fname = TestData.getLastName();
OR
String Fname =TestData.FirstName;
so I have 2 files called Employee.java and Write.java (These two are within the same package). Say within Employee.java I have
public class Employee {
private String firstName = "test";
private String lastName = "ing";
public Employee(String first, String last) {
firstName = first;
lastName = last;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
}
Then within my Write.java I want to create an object of type Employee called temp. Like
public void obtainInfo(Employee temp) {
String firstName = temp.firstName;
String lastName = temp.lastName;
}
However I get an error that tells me that it cannot find the symbol in the line that is.
public void obtainInfo(Employee temp) {
I was just wondering where I went wrong that I can't create an object within different files. Despite them being in the same package I can't access them?
I want to be able to incorporate this later on to help me build a text file from reading an array list, but I figured to first start with reading a single line from an object.
It sounds to me that you are trying to set something up so that you can make a copy of an Employee and be able to write the properties to a text file. This won't write to a text file but I think it may clear some things up for you.
public class Employee {
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Employee");
sb.append("{firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append('}');
return sb.toString();
}
}
TestClass.java
public class TestClass {
public static void main(String[] args){
//First we have to have one to copy
Employee emp = new Employee("Joe", "Dirt");
//Now we have a copy
Employee emp2 = new Employee(emp);
//Calls the Employee.toString() method and sends it to System.out
System.out.println("Employee 1 : " + emp);
System.out.println("Copy of Employee 1 : " + emp2);
}
}
Make sure that Write.java's class has the same level of access as Employee (IE: Public). If this is not the issue, I would show the code from Write.java specifically as that is most likely where the problem is coming from.
I'm a web developer dabbling in Java (again) and I'm having trouble with something.
Basically, I have a superclass Employee with two subclasses that extend it called Management and Programmer. The Employee class contains an array employees that is basically an array of Employee objects.
Here's the important snippets of two of the classes (Employee and Management) and the final main method. I'll explain the output at the bottom.
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
Now, I expect the system to print out "Kyle", but it prints out "Sheree". Any ideas???
private static String firstName;
You made firstName static, which means all instances share the same name. You'll need to remove the static modifier in order for different Employees to have different names. You'll also need to change the private access modifier to protected in order for the field to be inherited by subclasses.
private String firstName;
remove static;
Kyle was overridden by Sheree, that is why you are getting that output