Just to be transparent, this is an assignment for a class I am taking. I don't want someone else to do this for me, I'm just asking for a little nudge in the right direction. In this assignment, I need to grade a test that the user takes. The answer key is given. The thing that I am stuck on is how to input the char values into the array Driver.setAnswerSet. I've extensively searched the material given in the class, and I have tried many different possible solutions in Eclipse to solve this problem I'm having. To be exact, I'm not sure exactly how to input the values into the array. Putting the values into a regular array that is initialized in the same class is something I can do, but the addition of calling the array is becoming the end of me here. How would I go about placing input from the user into the array in question when it's being called from the other class? The current error I have is "The method setAnswerSet(char[]) in the type SU2018LAB6_DriverCandidate_Wayne is not applicable for the arguments (char)." Again, all I'm asking for is a piece of advice or push in the right direction here. Any help or assistance would be greatly appreciated. I also really do apologize if I'm asking what seems to be a stupid question.
This is the data class file that I have.
public class SU2018LAB6_DriverCandidate_Wayne {
private char[] keySet = {
'A','C','B','B','D','B','C','D','A','B',
'C','A','B','C','A','B','A','C','A','D',
'B','C','A','D','B'
};
//the answer key to be graded off of
private char[] answerSet;
//the answer key that is inputted by the user
private String lastName;
private String firstName;
private String socialNumber;
private String phone;
private String address;
//the getters and setter made by Eclipse
public char[] getKeySet() {
return keySet;
}
public void setKeySet(char[] keySet) {
this.keySet = keySet;
}
public char[] getAnswerSet() {
return answerSet;
}
public void setAnswerSet(char[] answerSet) {
this.answerSet = answerSet;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSocialNumber() {
return socialNumber;
}
public void setSocialNumber(String socialNumber) {
this.socialNumber = socialNumber;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
The driver class of the project:
public static void main(String[] args) {
SU2018LAB6_DriverCandidate_Wayne Driver = new SU2018LAB6_DriverCandidate_Wayne();
Scanner keyboard = new Scanner(System.in);
int test = 1;
int i;
int score;
while (test == 1) {
System.out.println("Welcome to the Online Driving Test");
System.out.println("To begin, enter your last name");
Driver.setLastName(keyboard.nextLine());
System.out.println("Enter your first name");
Driver.setFirstName(keyboard.nextLine());
System.out.println("Enter your SS number");
Driver.setSocialNumber(keyboard.nextLine());
System.out.println("Enter your phone number");
Driver.setPhone(keyboard.nextLine());
System.out.println("Enter your address");
Driver.setAddress(keyboard.nextLine());
//for (i = 0; i < Driver.getKeySet().length; i++) {
// System.out.println(Driver.getKeySet()[i]);
//}
System.out.println("Driver License Test");
System.out.println("There are 25 multiple choice questions");
System.out.println("You have to get at least 20 questions correct to pass");
System.out.println("---------------------------------");
// This is the area that I am having trouble with
for (i = 0; i < Driver.getKeySet().length; i++) {
System.out.println("Question " + (i + 1) + ": ");
Driver.setAnswerSet(keyboard.next().charAt(0));
}
for (i = 0; i < Driver.getKeySet().length; i++) {
System.out.println(Driver.getAnswerSet()[i]);
}
}
}
The error "The method setAnswerSet(char[]) in the type SU2018LAB6_DriverCandidate_Wayne is not applicable for the arguments (char)" is telling you that the setAnswerSet method is expecting an Array of characters, not a single character. The method let's you overwrite the reference to the array with a new one you pass in.
You have two options: Create an array filled with answers in SU2018LAB6_GradingDLTest_Wayne and "set" it as the new answerSet, or initialize answerSet in SU2018LAB6_DriverCandidate_Wayne and "get" it so you can start filling in the answers.
As it's currently written you can't just get the answerSet and update it because the array hasn't been initialized and is just a null reference.
Related
In my project of creating contacts and managing them, when i remove an object from an Array List in a for-loop, a Concurrent Modification Exception is being thrown(as mentioned in javadoc).
My question is how can i remove the object without getting "Concurrent Modification Exception"
I looked at similar posts but couldn't find the answer, some had complex code and many asked why a exception i s not thrown.
This question didn't help me/this specific problem
You can read the above link an help me out too(I'm rather new)
I am using jdk 14, ide:intelliJ,
I have created methods to manage contacts and get input but I'm only providing the method in which the exception is thrown.
public class Main {
private static ArrayList<Contact> contacts;
contacts = new ArrayList<>();
private static void deleteContact() {
System.out.println("Please enter contact name: ");
String name = scanner.next();
if (name.equals("")){
System.out.println("Please enter the name");
deleteContact();
}else{
boolean doesExist = false;
for(Contact c:contacts) { //Error pointed on this line.
if (c.getName().equals(name)) {
doesExist = true;
contacts.remove(c);
}
}
if (!doesExist){
System.out.println("There is no such contact");
}
}
showInitialOptions();
}
}
Important code from class 'Contact'
public class Contact {
private String name;
private int number;
private String email;
public Contact(String name, int number, String email ) {
this.name = name;
this.number = number;
this.email = email;
;
}
public String getName() {
return name;
}
}
You can use an Iterator to iterate over the ArrayList:
Iterator<Contact> it = contacts.iterator();
while(it.hasNext()){
Contact c = it.next();
if(c.getName().equals(name)){
doesExist = true;
it.remove();
}
}
For your particular problem, Change the line from
for(Contact c:contacts) {
To
for(int i=contacts.size()-1; i>-1; i--) {
It should work
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:\n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:\n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
#Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals and hashCode methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode and equals as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
Have to code a player class in java eclipse following these requirements
a) The Player class should have a default constructor and two custom constructors - one
that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It
should have a method called rollDice and getDiceScore that both simply delegate to the
PairOfDice class, which already has this functionality. You should also have an
appropriate toString() method.
c) Add a further void method setFullPlayerName(String) that accepts a single String
argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name
individually by extracting the relevant information and then calling the respective setter
methods of the Name class.
So far I have this
public class Player {
//Fields of the app
private String firstName;
private String lastName;
private Die red;
private Die blue;
//PlayerName and dice pair Default Constructor
public Player() {
firstName = "";
lastName = "";
red = new Die();
blue = new Die();
}
public Player(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Player(String firstName, String lastName,Die red,Die blue) {
this.firstName = firstName;
this.lastName = lastName;
this.red = red;
this.blue = blue;
}
// Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getlastName() {
return lastName;
}
#Override
public String toString() {
return "PairOfDice:[red=" + red + ", blue=" + blue + "]";
}
public void rollDice() {
red.roll();
blue.roll();
}
public int getDiceScore() {
return red.getScore() + blue.getScore();
}
public Die getRed() {
return red;
}
public Die getBlue() {
return blue;
}
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
}
Is my code correct? if not what changes do i have to make to correct it
There are several problems:
Dice not Die: private Die red;
It's better to name your variable using a noun: private Dice redDice;
Should have a space after a comma: , Dice redDice, Dice blueDice
setFullName should accept 1 string and call setFirstName and setLastName to set the name
Example of implementation:
void setFullName(String fullName) {
/// split full name into lastName and firstName
setFirstName(firstName);
setLastName(lastName);
}
Everything seems fine, but I think you forgot to define the roll() function. Besides that, everything else seems fine :)
I see a couple of issues with this code:
a) The Player class should have a default constructor and two custom constructors - one that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It should have a method called rollDice and getDiceScore that both simply delegate to the PairOfDice class, which already has this functionality. You should also have an appropriate toString() method.
If it's telling you that you need a Name object and a PairOfDice object, you can't just put in two Strings and two Dies and call that the same thing. You need to actually use the Name and PairOfDice classes.
c) Add a further void method setFullPlayerName(String) that accepts a single String argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name individually by extracting the relevant information and then calling the respective setter methods of the Name class
Instead of setFullPlayerName, you made a method called setFullName that does not do what it's supposed to do. It's supposed to accept a String and return void, and instead it accepts no parameters and returns a String. It looks like a getter instead of a setter.
Let's get this straight: This portion of the code:
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
it's misleading due to the fact that the method name it's saying that it's setting the name, BUT you're returning the name instead
So change it to this:
public void setFullPlayerName(String name) {
String[] splitted = name.split(" ");
firstname = splitted[0];
lastname = splitted[1]
}
And now it's unnecessary to add the method setFullPlayerName
BUT I see that you may need a method to return a full name, so:
public String getFullPlayerName() {
return firstname + " " + lastname;
}
Hopefully that'll resolve your issue :D
I have these two files, personalinfo.java which defines the personalInfo class, and testpersonalinfo.java which tests the class. When I try to access my getter methods from testpersonalinfo.java I receive an error that these methods are undefined. Can anybody please tell me why?
personalinfo.java:
public class personalInfo {
private String name;
private String address;
private int age;
private long phoneNumber;
personalInfo(){
name = "Default Name";
address = "Default Address";
age = 100;
phoneNumber = 0000000000;
}
personalInfo(String nam, String add, int ag, int phone){
name = nam;
address = add;
age = ag;
phoneNumber = phone;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getAge(){
return age;
}
public long getPhoneNumber(){
return phoneNumber;
}
public void setName(String nam){
this.name = nam;
}
public void setAddress(String add){
this.address = add;
}
public void setAge(int ag){
this.age = ag;
}
public void setPhoneNumber(long phone){
this.phoneNumber = phone;
}
}
testpersonalinfo.java:
import java.util.Scanner;
public class personalInfoExample {
public static void main(String[] args){
personalInfo[] pers = new personalInfo[3];
Scanner input = new Scanner(System.in);
String inName;
String inAddress;
int inAge;
long inPhoneNumber;
for(int i=0; i<3; i++){
pers[i] = new personalInfo();
System.out.printf("Please input the name for person %s: ", i );
inName = input.nextLine();
pers[i].setName(inName);
System.out.println(pers[i].getName);
System.out.printf("Please input the address for person %s: ", i );
inAddress = input.nextLine();
pers[i].setAddress(inAddress);
System.out.println(pers[i].getAddress);
System.out.printf("Please input the age for person %d: ", i );
inAge = input.nextInt();
pers[i].setAge(inAge);
input.nextLine();
System.out.println(pers[i].getAge);
System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
inPhoneNumber = input.nextLong();
pers[i].setPhoneNumber(inPhoneNumber);
System.out.println(pers[i].getPhoneNumber);
input.nextLine();
}
input.close();
}
}
The getters are functions, not fields; so to call them you need to use () (like in: pers[i].getAdress().
Also, class names should be capitalized, but it's not really important (just makes it easier to read.
As someone suggested in a comment, you should use an IDE, in case you are not doing it. The IDE will point you to the obvious little mistakes (both errors and convention mistakes) like the ones above, and save you a long time. If you don't know where to get started for that, search Eclipse or Netbeans. (Eclipse is my personal favourite).
EDIT: I just saw Eran commented the answer to your error, so if he posts it as an answer accept his first.
in all your sysout statements you are trying to access getter without () this.
please try this
System.out.println(pers[i].getName()); //change all your getters
instead of
System.out.println(pers[i].getName);
because getName() is a method not a Variable so always you need to use open-close braces () just after the method name
(either you defining or calling) .
please change all these methods (methods which raise an compile-time Error).
System.out.println(pers[i].getName);
System.out.println(pers[i].getAddress); //all these lines are causing of Compile time error.
System.out.println(pers[i].getAge);
System.out.println(pers[i].getPhoneNumber);
In case if you don't want to use getter method to access instance variable(Other than private variables) out side of the class defination, you can call instance variable-names directly on an instance object like
pers[i].name
For more on variables access control please refer java-doc
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}
According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");
I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.
Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.