Reputation: 600
I am new to programming and I have an assignment to write a class called Names. In my main method, I want to read in the entire name and pass it to my Names constructor. However, I keep getting type mismatch errors when passing the method data. What am I doing wrong??
import java.util.Scanner;
public class Names {
String first, middle, last;
/**
* @param args
*/
public Names(){
}
public Names(String first, String middle, String last){
first = this.first;
middle = this.middle;
last = this.last;
}
//returns the first name
public String getFirst(){
return first;
}
//returns the middle name
public String getMiddle(){
return middle;
}
//returns the last name
public String getLast(){
return last;
}
// Returns a string containing the person's full name in order,
public String firstMiddleLast(){
String ret = first + " " + middle + " " + last;
return ret;
}
public String lastFirstMiddle(){
String ret = last + ", " + first + " " + middle;
return ret;
}
public boolean equals(Names otherName){
if (first.equalsIgnoreCase(otherName.first) || middle.equalsIgnoreCase(otherName.middle)
|| last.equalsIgnoreCase(otherName.last))
return true;
else
return false;
}
public String initials(){
String retVal = first.substring(0) + "." + middle.substring(0) + "." + last.substring(0) + ".";
return retVal.toUpperCase();
}
public int length(){
String wholeName = (first+middle+last);
int retVal = wholeName.length();
return retVal;
}
public static void main(String[] args) {
Names person1 = new Names();
Names person2 = new Names();
Scanner scan = new Scanner(System.in);
System.out.println("Enter First Name: ");
person1.first = scan.next();
}
}
Upvotes: 0
Views: 3991
Reputation: 46408
Line #60 when I try to pass the String first to the constructor Names(String first, String middle, String last)
I dont see any compile time error's in your posted code but your code should be like this:
System.out.println("Enter First Name: ");
String firstname = scan.next();
System.out.println("Enter Middle Name: ");
String middlename = scan.next();
System.out.println("Enter Last Name: ");
String lastname = scan.next();
Names person1 =new Names(firstname, middlename, lastname);
And as noted by others your constructor declaration is not valid.
public Names(String first, String middle, String last){
this.first = first;
this.middle = middle;
this.last = last;
}
Upvotes: 2
Reputation: 4514
For one thing your constructor is backwards. Do this:
public Names(String first, String middle, String last){
this.first = first;
this.middle = middle;
this.last = last;
}
The this
reserved word always refers to the class/object you're working with. So when you refer to this.first
in the Names
class you are referring to Names' first variable, not the function parameter you've also named first.
Upvotes: 3