Naming objects incrementally - object

I was wondering how to name new objects something different each time a method is run
public class Horse extends Animal{
int horsenum = 0;
}
public void reproduce(Horse h){
horsenum ++;
Horse newHorse = new Horse(); //Here is where I would like to name the new horse "newHorse1, newHorse2, etc."

add a property of Horse.Name ofType string and name it what you will...

Related

How do you call a variable from another class's methods in java?

I'm currently trying to print a variable from one class in another class.
import java.util.HashMap;
import java.util.Random;
class Word{
Random r = new Random();
int low = 0;
int high = 25;
int result = r.nextInt(high-low) + low;
String word;
public void Mapski(){
HashMap<Integer, String> map = new HashMap<>();
map.put(0,"apple");
map.put(1,"banana");
map.put(2,"cantaloupe");
map.put(3,"durian");
map.put(4,"elderberry");
map.put(5,"fig");
map.put(6,"grapefruit");
map.put(7,"hashbrown");
map.put(8,"ice cream");
map.put(9,"jackfruit");
map.put(10,"kale");
map.put(11,"lettuce");
map.put(12,"mango");
map.put(13,"nachos");
map.put(14,"oatmeal");
map.put(15,"plum");
map.put(16,"quesadilla");
map.put(17,"raspberry");
map.put(18,"strawberry");
map.put(19,"tangelo");
map.put(20,"udon noodles");
map.put(21,"venison");
map.put(22,"watermelon");
map.put(23,"xigua");
map.put(24,"yogurt");
map.put(25,"zucchini");
String word = map.get(result);
this.word = word;
}
public void setWord(String word){
this.word = word;
}
public String getWord(){
return word;
}
}
I've tried using setters and getters but I just keep getting back that word is null. I know that the word variable in my Mapski() method is correct because when I add System.out.println(word) to the method Mapski(), it prints a random food from my list when I call the method in my main class with word.Mapski() after creating Word word = new Word();.
How can I make it so that when I'm in my main class I can call Mapski()'s word from class World with a food as the value instead of null? All help is appreciated. Thank you!

Passing HashMap as parameter into a subclass constructor

I've been struggling with trying to figure out the problem and fixing the error when I tried to pass HashMap into a constructor. My scenario is:
I've a Student class:
public class Student {
String name;
String major;
String level;
public Student (String name, String major, String level) {
this.name = name;
this.major = major;
this.level = level;
}
}
I've another class, called TA_Manager that is a subclass of Student. This TA_Manager class uses HashMap to collect the students (who are TA) from the Student class:
import java.util.HashMap;
public class TA_Manager extends Student {
HashMap<String, Student> TA;
public TA_Manager(HashMap<String, Student> TA) {
this.TA = TA;
}
}
In the main class, I've created three student objects and I put two of the students into the HashMap (they are TAs). Then I create a TA_Manager object and pass the HashMap into the TA_Manager class:
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
Student s1 = new Student("A", "CS", "Junior");
Student s2 = new Student("B", "IS", "Senior");
Student s3 = new Student("C", "CE", "Senior");
HashMap<String, Student> TA = new HashMap<String, Student>();
TA.put("TA1", s1);
TA.put("TA2", s2);
TA_Manager tamgr = new TA_Manager (TA);
}
}
When I run the main class, it returns error:
TA_Manager.java:6: error: constructor Student in class Student cannot be applied to given types;
public TA_Manager(HashMap<String, Student> TA) {
^
required: String,String,String
found: no arguments
I actually have searched this HashMap problem and I followed the solution given on how to pass the HashMap into the constructor:
Pass a HashMap as parameter in Java
and also from this link on how to pass a class as hashmap value:
Can HashMap contain custom class for key/value?
But I still get the error message. I don't know how to fix this error. Can anyone bring some light into this. Really appreciated.
The error is caused because java is trying to call the no-arg constructor of your Student class, but you only have a three argument public constructor.
The simplest solution is to create an empty public constructor for your student.
public Student(){
//do nothing and leave values as null.
}
This is not a very practical solution. The problem is a bit conceptual. Your TA class is a Student, but you don't give it a name major or level.
The next way to manage this would be to call the current constructor with some values.
public TA_Manager(HashMap<String, Student> TA) {
super( null, null, null);
this.TA = TA;
}
Now java knows to use the public constructor instead of the no-arg one. I left the values as null because I don't know what default values you would have. This is practical when there are useful default values that you wouldn't need to include during construction.
Personally, I would expect the TA to be a full student AND have a hashmap.
public TA_Manager (String name, String major, String level) {
super(name, major, level);
this.TA = new HashMap<>();
}
In this case you would create the manager, then add all of the students afterwards. It has the advantage that your TA_Manager is a fully formed student though.

Automapper mapping 2 entities to a single class

Just wondering if this is possible:
Say I have a ViewModel for comparing an old and new entity.
public class FooComparison
{
public string Name {get;set;}
public string OldName {get; set;}
public int Age {get; set;}
public int OldAge {get; set;}
...
}
I want to load 2 instances of Foo from the database and populate the FooComparison with the details from both instances.
For now, I have Mapper.CreateMap<Foo, FooComparison>() which will populate the Name, Age etc from the first entity - is there an easy way to populate the Oldxxx properties from the second entity without looping and manually updating them?
My suggestion would be to define a mapping from Tuple<Foo, Foo> to FooComparison:
Mapper.CreateMap<Tuple<Foo, Foo>, FooComparison>()
.ConvertUsing(x => new FooComparison
{
Name = x.Item2.Name,
OldName = x.Item1.Name,
Age = x.Item2.Age,
OldAge = x.Item1.Age,
...
});
Then use it like this:
Foo oldFoo = ...;
Foo newFoo = ...;
FooComparison comparison = Mapper.Map<FooComparison>(Tuple.Create(oldFoo, newFoo));
I appreciate that this loses the "auto" part of automapper, but really the big benefit you are getting by using automapper is that this mapping is defined in just one place in your software, not so much the auto part.
I have personally found this way of mapping via Tuple to work very well.

How to retrieve data using a strong typed model in LinqToSql

This code works fine.
using (ContextDB db = new ContextDB())
{
var custAcct = (from c in db.CustAccts
select new
{
c.AcctNo,
c.Company,
c.UserName
}).ToList();
But this one doesn't
public class CustAcct
{
public int AcctNo { get; set; }
public string Company { get; set; }
public string UserName { get; set; }
}
....
....
....
using (ContextDB db = new ContextDB())
{
CustAcct custAcct = (from c in db.CustAccts
select new
{
c.AcctNo,
c.Company,
c.UserName
}).ToList();
It returns this error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'EMailReader.Models.CustAcct'. An explicit conversion exists (are you missing a cast?)
I used Google, found many related topics but still couldn't put it to work using the available solutions
I just need to return data to a strong typed model.
EDITED:
After more research I found this solution bellow, but I wonder why I cannot retrieve directly in the list from LinqToSql.
List<CustAcct> temp = new List<CustAcct>();
IEnumerable<dynamic> items = custAcct;
foreach (var item in items)
{
temp.Add(new CustAcct()
{
AcctNo = item.AcctNo,
Company = item.Company,
UserName = item.UserName,
});
}
You are re defining those properties by creating new Class. And this will override LINQ2SQL generated class.
Just change "public class CustAcct" to "public partial class CustAcct".
This will solve your problem, and you do not need to define those properties again. Remove those from your class. Those will be automatically create for you.
If you can just post your class, and I will change it for you.
//Shyam

Name generator using Generics

I am trying to generate a Name based on type of an object. In my system, I have,
class Employee {}
Class ContractEmp:Employee{}
class Manager:Employee{}
I am trying to generate name which looks like ContractEmp1 Where 1 will come from incrementer. I am trying to use Generics.
Any Help
Thank you,
With an extension method you could do something like this:
public static class NameExtension
{
private static Dictionary<string, int> counters = new Dictionary<string, int>();
public static string MakeUpName<T>(this T #object)
{
var t = typeof(T);
if ( ! counters.ContainsKey(t.FullName))
counters[t.FullName] = 0;
return t.Name + counters[t.FullName]++;
}
}
Test:
[TestFixture]
class NameTest
{
[Test]
public void test()
{
Console.WriteLine(new NameTest().MakeUpName());
Console.WriteLine(new NameTest().MakeUpName());
Console.WriteLine(new NameTest().MakeUpName());
Console.WriteLine(new NameTest().MakeUpName());
}
}
Output:
NameTest0
NameTest1
NameTest2
NameTest3
You can use a private static int in the Employee class which gets incremented on each constructor call. Combining this number with the typeof(this).Name value you can generate the names as described. Do note that the counter will count for all Employee extending classes so if you want an consecutive list of numbers for each Employee extending class, a specific counter should be implemented for every extending class. Also, the counters will be set to zero each time the application restarts.
public Class ContractEmp:Employee{
private static int counter = 1;
private String name = "";
public ContractEmp() {
name = typeof(this).Name + counter++;
}
}
Something like this should work!

Resources