How to print array contents with a getter? - java

I'm trying to print contents of an array stored inside an ArrayList .
My constructor parameters are (String,String,String,String[], String, String).
When creating add. function to the arrayList the contents are stored in the String[] parameter.
But when using a getter method to return the String[], it launches an error: "Type mismatch: cannot convert from String to String[]".
Eclipse solution is to change getter method to String, but then the add. function doesn't work because the parameter should be String[].
Also all the .toString, .clone, etc, returns memory location not array contents.
Desperate for help!!
Here is part of my code:
public class NewRegandLogin {
private String alumniFirstName;
private String alumniLastName;
private String alumniId;
private Scanner scanner = new Scanner(System.in);
private String linkedInPage;
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
private String alumniIdImput;
private String passwordImput;
private String permanentPasword;
private String[] coursesList;
public NewRegandLogin(String alumniFirstName, String alumniLastName,String alumniId, String[] coursesList, String linkedInPage, String permanentPasword) {
this.alumniFirstName=alumniFirstName;
this.alumniLastName = alumniLastName;
this.alumniId = alumniId;
this.coursesList = coursesList;
this.linkedInPage = linkedInPage;
this.permanentPasword = permanentPasword;
}
public void setAlumniCourses() {
coursesList = new String[10];
for (int i=0; i < coursesList.length; i++) {
if(coursesList[i]==null) {
System.out.println("Completed Course Name: ");
coursesList[i]=scanner.next();
}
if(coursesList[i].equals("s") || coursesList[i].equals("S")) {
break;
}
}
}
public String[] getCourses() {
return Arrays.toString(coursesList);
}
main
public class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
public static void main(String[] args) {
System.out.println("Please make a list of completed Courses: (Enter S to stop adding courses) ");
newRegAndLogin.setAlumniCourses();
loginInformation.add(newRegAndLogin);
printAlumniProfile();
}
public static void printAlumniProfile() {
for (int i = 0; i<NewRegandLogin.loginInformation.size();i++) {
System.out.println(((i+1)+"-"+ NewRegandLogin.loginInformation.get(i)));
System.out.println();
}
}
}
Output:
1-Alumni Name: Geri Glazer
Alumni ID: geri.glazer.she-codes
Courses completed: [Ljava.lang.String;#3dd3bcd

public String[] getCourses() {
return Arrays.toString(coursesList);
}
Arrays.toString returns a String, not a String[]. If you want to return a String, change the return type to String.
public String getCourses() {
return Arrays.toString(coursesList);
}
If you want to return a single-element array, containing the string representation of coursesList, you can wrap the String in an array:
public String[] getCourses() {
return new String[]{Arrays.toString(coursesList)};
}
If you want to return the array, just return the array:
public String[] getCourses() {
return coursesList;
}
Or, more safely, return a defensive copy of the array (to prevent the caller changing the internal array):
public String[] getCourses() {
return Arrays.copyOf(coursesList, coursesList.length);
}

Related

Populating array in sub class with parent class getter java

Sorry as I know this is obvious but I cant figure it out!
I have a parent class named 'Set', representing a set of a tennis match.
public class Set {
private String set1;
private String set2;
private String set3;
//private Object[] match;
public Set() {
setSet1(set1);
setSet2(set2);
setSet3(set3);
}
public void setSet1(String set1) {
this.set1 = set1;
}
public String getSet1() {
return set1;
}
public void setSet2(String set2) {
this.set2 = set2;
}
public String getSet2() {
return set2;
}
public void setSet3(String set3) {
this.set3 = set3;
}
public String getSet3() {
return set3;
}
public String toString(){
return String.format("set1: %s, set2: %s, set3: %s", set1, set2, set3);
}
}
And a sub class of 'Set' named 'SingleSet', where i try to add the sets into an array named 'game':
public class SingleSet extends Set{
private Object homePlayer;
private Object awayPlayer;
private String[] game;
public SingleSet(Object homePlayer, Object awayPlayer){
super();
game = new String[3];
game[0] = super.getSet1();
game[1] = super.getSet2();
game[2] = super.getSet3();
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
public void setHomePlayer(Object homePlayer) {
this.homePlayer = homePlayer;
}
public Object getHomePlayer() {
return homePlayer;
}
public void setAwayPlayer(Object awayPlayer) {
this.awayPlayer = awayPlayer;
}
public Object getAwayPlayer() {
return awayPlayer;
}
public void setGame(String[] game) {
this.game = game;
}
public String[] getGame() {
return game;
}
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
}
And this is where I am trying to add the Sets from my parents class into my sub class (this is for FXML, so the code is in my controller):
public void submit() {
SingleSet game1 = new SingleSet(homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue());
game1.setSet1(set1Box1.getText());
game1.setSet2(set1Box2.getText());
game1.setSet3(set1Box3.getText());
System.out.println(game1);
When I print the result, all my values are null. I tried printing them individually and that worked fine, so I know the 'set1Box.getText()' is working fine.
Again sorry for any obvious rookie error!
I've updated my code and same issue. Thank you for the composition answer, I will need it for my project, but this is a IS-A relationship
Make sure that the toString() methods of the following attributes exist and return a correct string.
It seems as if there is no way to get a String from homePlayer, awayPlayer and all indices of game[x].
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}

Take one variable from arrayList and add it to new arrayList

I have a dog class with name, breed, age and weight.
I also have an arraylist which contains objects with these four attributes. Now I want to create an auction(which also have an own class) and I want to get the name from the dogArraylist and add it to a new Arraylist of auctions.
How can I do this? Is it possible?
private void newAuction(ArrayList<AuctionHouse> auctionHouse) {
boolean foundIt = false;
System.out.println("Enter the name of the dog> ");
String nameOfDog = input.nextLine();
for(int i = 0; i < dog.size(); i++) {
if(dog.get(i).getName().equalsIgnoreCase(nameOfDog)) {
foundIt = true;
if(foundIt) {
auctionHouse.add(i);
}
}
}
if(!foundIt) {
System.out.println("Error: no such dog ");
}
}
AuctionHouse class:
public class AuctionHouse {
private String auctionDog;
public AuctionHouse(String auctionDog) {
this.auctionDog = auctionDog;
}
public String getAuctionDog() {
return auctionDog;
}
public void setAuctionDog(String name) {
this.auctionDog = name;
}
public String toString() {
return String.format("%s", auctionDog);
}
}
Use enhanced for-loop instead and note: foundIt variable and if(foundIt) is redundant. Also newAuction() method should probably takes a list of dog as a parameter and return new list of auction. I guess it is more logical. Try:
private List<AuctionHouse> newAuction(List<Dog> dogs) {
List<AuctionHouse> auctionHouse = new ArrayList<>();
String nameOfDog = new Scanner(System.in).nextLine();
for (Dog d : dogs) {
if (d.getName().equalsIgnoreCase(nameOfDog)) {
auctionHouse.add(new AuctionHouse(d.getName()));
}
}
if (auctionHouse.isEmpty()) {
System.out.println("not found");
}
return auctionHouse;
}

Search ArrayList for keywords and return location

I am trying to write a method that search an ArrayList of a particular word and then prints the location of all of the occurrences of the word.
Here is what I have, it works fine until I enter the word I want to search but then it prints nothing:
import java.util.ArrayList;
import java.util.Scanner;
public class W7E2 {
public static void main(String[]args) {
System.out.println("Please anter words: ");
Scanner sc = new Scanner(System.in);
String []w = sc.nextLine().split(" ");
ArrayList<Words> word = new ArrayList<Words>();
for(int i=0; i<w.length; i++) {
word.add(new Words(w[i]));
}
System.out.println(word);
System.out.println("Please enter the word you want to search: ");
String search = sc.nextLine();
for(Words ws: word) {
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
}
}
static class Words{
private String wor;
private static int number = -1;
public Words(String wor) {
this.wor = wor;
number++;
}
public int getLocation() {
return number;
}
public String toString() {
return wor;
}
}
}
In your if statement to see if the ArrayList contains the word you have:
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
But ws is a Word object and unless you override the equals() method, it will never equal the String object. You need to do something like:
if(ws.getwor().equals(search)) {
System.out.println(ws.getLocation());
}
This is assuming that you create a get method for wor.
Besides GBlodgett's answer,the number in class Word is static,so each Word instance will have a same number,you need to use a no-static variable to store the location
static class Words{
private String wor;
private static int number = -1;
private int location;
public Words(String wor) {
this.wor = wor;
number++;
location = number;
}
public int getLocation() {
return location;
}
public String toString() {
return wor;
}
}
Your code should be like this :
for(Words ws: word) {
if(ws.toString().equals(search)) { //to change
System.out.println(ws.getLocation());
}
}
ws is the object of Words class, you have to change it to toString()
What you should do is instead of
ws.equals(search)
you need to add
ws.toString().equals(search)
as you return the word from the
toString()
method in the Words Class.
So the code should look something like this,
for(Words ws: word) {
if(ws.toString().equals(search)) {
System.out.println(ws.getLocation());
}
}

Can't input data in my array

Keeps saying "incompatible types String[] cannot be converted to string"
do I have something wrong?
public class TimeCard {
private int employeeNum;
private String[] clockInTimes = new String[14];
private String[] clockOutTimes = new String[14];
private float[] decimalClockIn = new float[14];
private float[] decimalClockOut = new float[14];
private float[] timeElapsed = new float[14];
public String getClockInTimes()
{ //im getting the error here
return clockInTimes;
}
public void setClockInTimes(String[] value)
{ //getting the error here
clockInTimes = value;
}
}
Update now it wont let me enter a string within the array.
I'm trying to do it like this:
public class TestTimeCard {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
TimeCard josue = new TimeCard();
System.out.println("Enter Monday Clock In Times:");
josue.setClockInTimes(reader.next());
}
}
You are returning array but return type is defined as just string.
public String[] getClockInTimes()
{ //im getting the error here
return clockInTimes;
}

Sorting a list of constructed objects alphabetically using collections.sort

I need to take a collection of objects using the CompareTo() command, and then have these stored in a list, and then use the collections.sort() command to sort them alphabetically by last name, then by first name if the last name isn't strong enough, and then print off the entire list at the end.
This is the code I have so far:
package sortlab;
import java.io.*;
import java.util.*;
public class SortLab {
public static void main(String[] args) throws Exception {
File youSaidUseOurRelativeFileNameForStudentData =
new File("C:/My192/SortLabProj/src/sortlab/student.data");
Scanner sc = new Scanner(youSaidUseOurRelativeFileNameForStudentData);
ArrayList<Student> StudentList = new ArrayList<Student>();
while (sc.hasNextLine()) {
Student testStudent = new Student(sc.next(), sc.next(), sc.next());
sc.nextLine();
StudentList.add(testStudent);
}
}
}
And the next class:
package sortlab;
import java.util.*;
class Student implements Comparable<Student> {
private String first;
private String last;
private String address;
public Student(String f, String l, String a) {
first = f;
last = l;
address = a;
}
#Override
public int compareTo(Student other) {
if (last.hashCode() > other.last.hashCode()) return 1;
if (last.hashCode() < other.last.hashCode()) return -1;
if (first.hashCode() > other.first.hashCode()) return 1;
if (first.hashCode() < other.first.hashCode()) return -1;
return 0;
}
}
If you want to compare them ASCIIbetically use the String.compareTo method. It would never occur to me to compare hashCodes.
If you want to ignore case, you can use String.compareToIgnoreCase
First of all I would add getters for first and last name. Then try this code:
#Override
public int compareTo(Student other) {
int result = l.compareTo(other.getLastName());
if (result == 0) {
return f.compareTo(other.getFirstName());
} else {
return result;
}
}
Then add a toString() method to your Student class:
#Override
public String toString() {
return f+" "+l+", "+a;
}

Categories