How to get generic list intance's specific item - java

I don't know how to get a specific item for a generic list instance. Suppose I have something like this;
public class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
and another class;
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1 + " - ";
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}
The output I want to get is the text part of the column but I am not getting it. Is there a simple way of doing it ?

I cannot get why you cannot use getName() method?
It should work:
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - ";
}
System.out.println("Cols: " + str);
}

Below code is working , Output :
Cols: yo - mo -
I guess this is what you are expecting.
package com.vipin.test;
import java.util.*;
class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
}
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
}
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - "; //used getName()
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}

Related

Using toString() method from child class

Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?
The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}

Using CSV premier league match data to update an object value java and return to CSV

I am new to Java and I am attempting to manipulate some football match data in order to get a more in-depth understanding of the results. I have managed to get it to read from the CSV and I can get the individual values. The CSV format is like this fopr about 400 rows:
Arsenal,Leicester,4,3,H
Brighton,Man City,0,2,A
Chelsea,Burnley,2,3,A
Crystal Palace,Huddersfield,0,3,A
Everton,Stoke,1,0,H
Southampton,Swansea,0,0,D
What I have struggled with is to retrieve the home team and away teams(objects and unsure how to match the string from the CSV to them): current points, league position goal, difference along with the match in a row in excel (I plan to use an artificial neural network to predict matches from this data) then I would like to match and update the correct object of each team e.g.if home team is Arsenal and they win 2-0 update Team Arsenal() to have 3 more points, 2 more goals scored, update league table position. Once this is done it will read the next result and repeat.
I know this is a lot but I am really struggling on these parts so would really appreciate some help for a newbie to java.
Here is my current code:
InputHere.java:
package BasicP;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class InputHere {
public static void main(String[] args) {
List<Match> matches = new ArrayList<>();
Path logFile = Paths.get("C:\\Users\\Lewys\\Documents", "FinalofFootballDataws.csv");
try (BufferedReader read
= Files.newBufferedReader(logFile, StandardCharsets.US_ASCII)) {
String firstLine = read.readLine();
while (firstLine != null) {
String[] variables = firstLine.split(",");
String homeName = variables[0];
String awayName = variables[1];
String strHomeScore = variables[2];
String strAwayScore = variables[3];
int homeScore = Integer.parseInt(strHomeScore);
int awayScore = Integer.parseInt(strAwayScore);
firstLine = read.readLine();
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
return;
}
}
Team.java:
public class Team {
private String teamName;
private int numberWin;
private int numberDraw;
private int numberLoss;
private int matchesPlayed;
private int points;
private int goalsScored;
private int goalsConceded;
private int tablePosition;
public Team(String teamName, int numberWin, int numberDraw,
int numberLoss, int matchesPlayed, int points,
int goalsScored, int goalsConceded, int tablePosition) {
}
public int getNumberWin() {
return numberWin;
}
public int getNumberDraw() {
return numberDraw;
}
public int getNumberLoss() {
return numberLoss;
}
public int getMatchesPlayed() {
return matchesPlayed;
}
public int getPoints() {
return points;
}
public int getGoalsScored() {
return goalsScored;
}
public int getGoalsConceded() {
return goalsConceded;
}
public int getTablePosition() {
return tablePosition;
}
public void setNumberWin(int i) {
numberWin = numberWin + i;
}
public void setNumberDraw(int i) {
numberDraw = numberDraw + i;
}
public void setNumberLoss(int i) {
numberLoss = numberLoss + i;
}
public void setMatchesPlayed(int i) {
matchesPlayed = matchesPlayed + i;
}
public void setPoints(int i) {
points = points + i;
}
public void setGoalsScored(int i) {
goalsScored = goalsScored + i;
}
public void setGoalsConceded(int i) {
goalsConceded = goalsConceded + i;
}
public void settablePosition(int i) {
tablePosition = i;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
I try solve your issue.
Firt a write a CSVReader, but I suggest you to try using a specific library for it to better manage all csv format.
public class FootballMatchCSVReader {
public List<FootballMatch> read(String filePath) throws IOException {
return readAllLines(filePath).stream().map(line -> mapToFootballMatch(line.split(","))).collect(toList());
}
private List<String> readAllLines(String filePath) throws IOException {
return Files.readAllLines(Paths.get(filePath));
}
private FootballMatch mapToFootballMatch(String[] args) {
return new FootballMatch(args[0],args[1],Integer.valueOf(args[2]),Integer.valueOf(args[3]),args[4].charAt(0));
}
}
That return a List of FootballMatch
public class FootballMatch {
private String homeTeam;
private String awayTeam;
private int homeTeamScore;
private int awayTeamScore;
private char finalResult;
public FootballMatch(String homeTeam, String awayTeam, int homeTeamScore, int awayTeamScore, char winner) {
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.homeTeamScore = homeTeamScore;
this.awayTeamScore = awayTeamScore;
this.finalResult = winner;
}
public String getHomeTeam() {
return homeTeam;
}
public void setHomeTeam(String homeTeam) {
this.homeTeam = homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public void setAwayTeam(String awayTeam) {
this.awayTeam = awayTeam;
}
public int getHomeTeamScore() {
return homeTeamScore;
}
public void setHomeTeamScore(int homeTeamScore) {
this.homeTeamScore = homeTeamScore;
}
public int getAwayTeamScore() {
return awayTeamScore;
}
public void setAwayTeamScore(int awayTeamScore) {
this.awayTeamScore = awayTeamScore;
}
public char getFinalResult() {
return finalResult;
}
public void setFinalResult(char finalResult) {
this.finalResult = finalResult;
}
#Override
public String toString() {
return "FootballMatch{" +
"homeTeam='" + homeTeam + '\'' +
", awayTeam='" + awayTeam + '\'' +
", homeTeamScore=" + homeTeamScore +
", awayTeamScore=" + awayTeamScore +
", finalResult=" + finalResult +
'}';
}
}
Now I write a FootballMatchStatisticsEngine that compute the TeamStatistic for each match
public class TeamStatistic {
private String teamName;
private int numberWin;
private int numberDraw;
private int numberLoss;
private int matchesPlayed;
private int points;
private int goalsScored;
private int goalsConceded;
private int tablePosition;
public TeamStatistic(String teamName, int numberWin, int numberDraw, int numberLoss, int matchesPlayed, int points, int goalsScored, int goalsConceded, int tablePosition) {
this.teamName = teamName;
this.numberWin = numberWin;
this.numberDraw = numberDraw;
this.numberLoss = numberLoss;
this.matchesPlayed = matchesPlayed;
this.points = points;
this.goalsScored = goalsScored;
this.goalsConceded = goalsConceded;
this.tablePosition = tablePosition;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public int getNumberWin() {
return numberWin;
}
public void setNumberWin(int numberWin) {
this.numberWin = numberWin;
}
public int getNumberDraw() {
return numberDraw;
}
public void setNumberDraw(int numberDraw) {
this.numberDraw = numberDraw;
}
public int getNumberLoss() {
return numberLoss;
}
public void setNumberLoss(int numberLoss) {
this.numberLoss = numberLoss;
}
public int getMatchesPlayed() {
return matchesPlayed;
}
public void setMatchesPlayed(int matchesPlayed) {
this.matchesPlayed = matchesPlayed;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public int getGoalsScored() {
return goalsScored;
}
public void setGoalsScored(int goalsScored) {
this.goalsScored = goalsScored;
}
public int getGoalsConceded() {
return goalsConceded;
}
public void setGoalsConceded(int goalsConceded) {
this.goalsConceded = goalsConceded;
}
public int getTablePosition() {
return tablePosition;
}
public void setTablePosition(int tablePosition) {
this.tablePosition = tablePosition;
}
#Override
public String toString() {
return "TeamStatistic{" +
"teamName='" + teamName + '\'' +
", numberWin=" + numberWin +
", numberDraw=" + numberDraw +
", numberLoss=" + numberLoss +
", matchesPlayed=" + matchesPlayed +
", points=" + points +
", goalsScored=" + goalsScored +
", goalsConceded=" + goalsConceded +
", tablePosition=" + tablePosition +
'}';
}
}
public class FootballMatchStatisticsEngine {
public List<TeamStatistic> computeTeamStatistics(List<FootballMatch> footballMatches) {
List<TeamStatistic> teamStatistics = getTeamStatistics(footballMatches);
updatePosition(teamStatistics);
return teamStatistics;
}
private void updatePosition(List<TeamStatistic> teamStatistics) {
/*
This function apply the relative table position to each TeamStatistics.
*/
IntStream.range(0,teamStatistics.size()).forEach(i -> teamStatistics.get(i).setTablePosition(i+1));
}
private List<TeamStatistic> getTeamStatistics(List<FootballMatch> footballMatches) {
/*
The flat operation explode each match into two different TeamStatistics. One for home team and one for away team.
After I compute the groupBy operation over team name and reduce the resulting list of Team statistics sumurizing her data.
*/
return footballMatches
.stream()
.flatMap(fm -> footballMatchtoTeamStatistics(fm).stream())
.collect(groupingBy(TeamStatistic::getTeamName, reducing(getTeamStatisticReduceOperation())))
.values().stream().map(Optional::get)
.sorted(comparingInt(TeamStatistic::getPoints).reversed())
.collect(Collectors.toList());
}
private BinaryOperator<TeamStatistic> getTeamStatisticReduceOperation() {
return (x, y) ->
new TeamStatistic(
x.getTeamName(),
x.getNumberWin() + y.getNumberWin(),
x.getNumberDraw() + y.getNumberDraw(),
x.getNumberLoss() + y.getNumberLoss(),
x.getMatchesPlayed() + y.getMatchesPlayed(),
x.getPoints() + y.getPoints(),
x.getGoalsScored() + y.getGoalsScored(),
x.getGoalsConceded() + y.getGoalsConceded(), 0);
}
private List<TeamStatistic> footballMatchtoTeamStatistics(FootballMatch footballMatch) {
return Arrays.asList(
new TeamStatistic(
footballMatch.getHomeTeam(),
footballMatch.getFinalResult() == 'H' ? 1 : 0,
footballMatch.getFinalResult() == 'D' ? 1 : 0,
footballMatch.getFinalResult() == 'A' ? 1 : 0,
1,
footballMatch.getFinalResult() == 'H' ? 3 : footballMatch.getFinalResult() == 'D' ? 1 : 0,
footballMatch.getHomeTeamScore(),
footballMatch.getAwayTeamScore(),
0),
new TeamStatistic(
footballMatch.getAwayTeam(),
footballMatch.getFinalResult() == 'A' ? 1 : 0,
footballMatch.getFinalResult() == 'D' ? 1 : 0,
footballMatch.getFinalResult() == 'H' ? 1 : 0,
1,
footballMatch.getFinalResult() == 'A' ? 3 : footballMatch.getFinalResult() == 'D' ? 1 : 0,
footballMatch.getAwayTeamScore(),
footballMatch.getHomeTeamScore(),
0)
);
}
}
To test this code I write a file with the follow lines:
Arsenal,Leicester,4,3,H
Man City,Leicester,2,1,H
Brighton,Man City,0,2,A
Chelsea,Arsenal,0,2,A
Chelsea,Burnley,2,3,A
Crystal Palace,Huddersfield,0,3,A
Everton,Stoke,1,0,H
Southampton,Swansea,0,0,D
running the follow code
FootballMatchCSVReader reader = new FootballMatchCSVReader();
FootballMatchStatisticsEngine statisticsEngine = new FootballMatchStatisticsEngine();
try {
List<FootballMatch> footbalMatches = reader.read("src/test/resources/input.txt");
List<TeamStatistic> teamStatistics = statisticsEngine.computeTeamStatistics(footbalMatches);
teamStatistics.forEach(t -> System.out.println(t));
} catch (IOException e) {
e.printStackTrace();
}
This is the output
TeamStatistic{teamName='Arsenal', numberWin=2, numberDraw=0, numberLoss=0, matchesPlayed=2, points=6, goalsScored=6, goalsConceded=3, tablePosition=1}
TeamStatistic{teamName='Man City', numberWin=2, numberDraw=0, numberLoss=0, matchesPlayed=2, points=6, goalsScored=4, goalsConceded=1, tablePosition=2}
TeamStatistic{teamName='Huddersfield', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=3, goalsConceded=0, tablePosition=3}
TeamStatistic{teamName='Everton', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=1, goalsConceded=0, tablePosition=4}
TeamStatistic{teamName='Burnley', numberWin=1, numberDraw=0, numberLoss=0, matchesPlayed=1, points=3, goalsScored=3, goalsConceded=2, tablePosition=5}
TeamStatistic{teamName='Southampton', numberWin=0, numberDraw=1, numberLoss=0, matchesPlayed=1, points=1, goalsScored=0, goalsConceded=0, tablePosition=6}
TeamStatistic{teamName='Swansea', numberWin=0, numberDraw=1, numberLoss=0, matchesPlayed=1, points=1, goalsScored=0, goalsConceded=0, tablePosition=7}
TeamStatistic{teamName='Stoke', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=1, tablePosition=8}
TeamStatistic{teamName='Crystal Palace', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=3, tablePosition=9}
TeamStatistic{teamName='Brighton', numberWin=0, numberDraw=0, numberLoss=1, matchesPlayed=1, points=0, goalsScored=0, goalsConceded=2, tablePosition=10}
TeamStatistic{teamName='Chelsea', numberWin=0, numberDraw=0, numberLoss=2, matchesPlayed=2, points=0, goalsScored=2, goalsConceded=5, tablePosition=11}
TeamStatistic{teamName='Leicester', numberWin=0, numberDraw=0, numberLoss=2, matchesPlayed=2, points=0, goalsScored=4, goalsConceded=6, tablePosition=12}

Created add() method to insert objects into an array and all i get are null values

this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}

Making a class-array dynamic in Java

I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

How to name a component with a string

I have a problem with that i can't get my string to be named with a string! here is my code.
public class Load {
int num = 0;
public String getstuff(){
num++;
String snum = new String("" + num);
return snum;
}
String name = this.getstuff();
public void AddString(String f, int v){
String name = this.name;
String name = new String(f + v);
}
public Load(String s){
}
}
Avoid using String constructor.
public class Load {
int num = 0;
public String getstuff() {
num++;
return "" + num;
}
String name = this.getstuff();
public void AddString(String f, int v){
this.name = this.name + f + v;
// Or
// this.name = f + v;
// Whichever behavior you want.
}
public Load(String s){
}
}
Hope this helps.
Good luck.

Categories