I want to create an object of a class by referring to its object, I think. I've been able to make it in C# but in Java it wont work. This is what I want to do:
controller.getDal().getStudentData().getPerson() = new Person(student.getIdNumber(), student.getName(), student.getAddress(), student.getTel());
But I get a error message saying:The left-hand side of an assignment must be a variable
How can I fix the problem? I've tried like doing like this:
register.AddStudent(controller.getDal().getStudentData().getPerson());
and then
System.out.println("Show info: " + controller.getDal().getStudentData().getPerson());
and the output I get is : Person#7cd0a5d9
Java doesn't have the Property syntax that c# does. you have to use a setter.
controller.getDal().getStudentData().setPerson(
new Person(/*blah blah blah*/)
);
if you control whatever type getStudentData returns, than you might have to make one.
public void setPerson(Person newPerson)
{
this.person = newPerson;
}
Right now you are trying to set a new person using a get method. You cannot set an object to a function. You are on the right track with your code:
register.AddStudent(controller.getDal().getStudentData().getPerson());
I do wonder however if in your code that a student and a person are the same thing. You did not provide enough code for me to test and to give you an guaranteed answer, but I would assumg that your code should be more like this:
register.AddStudent(controller.getDal().getStudent());
This way you are getting the student and then adding the student. I'm not sure what you are trying to accomplish but you should really be looking into set methods such as something like:
Person p = controller.getDal().getStudentData().getPerson();
p.setIdNumber = 0011559966
p.setAddress('123 C St');
Or even something along the lines of:
register.AddStudent(new Student("Billy", "Crystal", "123 C st"));
Anyway, if you had more code, I would be able to help you more, but that is the best I can think of without any real context
About:
System.out.println("Show info: " + controller.getDal().getStudentData().getPerson());
You must override the toString() method inside the Person class to the fields or string representation you want to see upon printing.
An example could be:
#Override
public String toString() {
return "Name: " + this.getName() + " Id Num: " + this.getIdNumber();
}
Related
I'm using annotation processing and javapoet library to generate some source code.
Say, I've a
VariableElement fieldElement
and if
System.out.println("type:- " + fieldElement.asType().toString());
prints
type:- java.util.Set<com.example.demo.test.model.User>
How do I get the Set class and User class so I can do something like this with javapoet?
ClassName user = ClassName.get("com.example.demo.test.model", "User");
ClassName set = ClassName.get("java.util", "Set");
TypeName setOfUsers = ParameterizedTypeName.get(set, user);
Some string comparison would get the job done, but doesn't seem like the ideal approach.
You can try below code.
For getting that User class you can use fieldElement.getEnclosingElement(), it will give you class name with full package name.
Now if you want only name of that class you can use enclosingElement.getSimpleName().
And to get enclosedByElement you can use TypeSymbol.Simply cast fieldElement.asType() to Type and get tsym attribute.
VariableElement fieldElement;
Symbol.TypeSymbol containerForEnclosingElement=((Type)fieldElement.asType()).tsym;
Element enclosingElement=fieldElement.getEnclosingElement();
System.out.println("containerForEnclosingElement:- " + containerForEnclosingElement);
System.out.println("enclosingElement:- " + enclosingElement);
System.out.println("enclosingElement Name:- " + enclosingElement.getSimpleName());
System.out.println("fieldElement without root Type:- "+((Type) fieldElement.asType()).getTypeArguments().get(0));
Above code will print output as below.
containerForEnclosingElement:- java.util.Set
enclosingElement:- com.example.demo.test.model.User.
enclosingElement Name:- User
fieldElement without root Type:- com.example.demo.test.model.User
You can also create one Utility method to get this two values.
This will help you.
this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.
I currently have a toString method, similar to the one below. Please ignore that the Objects are only temporarily named. I have done this so that there is no confusion between the types of each variable etc.:
#Override
public String toString() {
for(Object object : ArrayList) {
System.out.println("This object is a " + object.getVariableA() + " and a " + object.getVariableB() + ".");
}
return null;
}
However the toString method requires me to return a value. I would obviously just want to return the Strings that I'm printing, although if I place a return statement there, it will only print one Object and not all of the ones I am looping through. What would be the best way to print all these values and not simply return null as I don't want this printing out after all the Objects? I also want to ensure that each of these Objects are printed on separate lines like they currently are so please don't suggest solutions that include one long joined String without line breaks as this is not suitable in this situation.
Thanks in advance!
toString shouldn't output anything at all. Its job is to return an appropriate string representation of the relevant object, not to output that representation anywhere. That's outside its problem domain.
Instead, build and return a string (probably by using a StringBuilder).
E.g., something like:
#Override
public String toString() {
StringBuilder sb = new StringBuilder(some_appropriate_size);
for(Object object : ArrayList) {
sb.append("This object is a ")
.append(object.getVariableA())
.append(" and a ")
.append(object.getVariableB())
.append(".\n");
}
return sb.toString();
}
I also want to ensure that each of these Objects are printed on separate lines like they currently are so please don't suggest solutions that include one long joined String as this is not suitable in this situation.
The above puts the items from the array list on separate "lines" (via the \n). But "one long joined String" is the only appropriate thing for toString to do. If you want a different result, you must use a different method, rather than breaking the contract of toString.
You could create a String and add what you want each iteration:
#Override
public String toString() {
String result = "";
for(Object object : ArrayList) {
result += "This object is a " + object.getVariableA() + " and a " + object.getVariableB() + ".\n");
}
return result;
}
Don't forget to add the "\n" new-line character, so you print each "partial result" in one different line.
You state in your question that:
I also want to ensure that each of these Objects are printed on separate lines like they currently are so please don't suggest solutions that include one long joined String as this is not suitable in this situation.
Then you probably shouldn't be using toString(); that's not what's it's for. It is for returning a single string that is some representation of the object. It should never be outputting anything.
Add a getter to your class that returns the List of objects, output them as you would like. If you really wanted to make the class self-printing, add a print(OutputStream os) method that takes the supplied OutputStream (or maybe a PrintStream instead) and will do so.
I am somewhat new to JAVA. I've been working with it in college, but I have to admit, my instructor is of absolutely no help. She hardly knows JAVA herself, but that is another issue all in itself. I've been confused as to how methods and classes work. I'm creating this program that uses two files, one "main" file, and a "test" file. I can't seem to get the "main" file correct, as the compiler keeps telling me that it cannot find the symbols, even though they are. In the "test" file, I can't seem to get the compiler to recognize the methods from the "main" file. I have made sure that the files are in the same folder. I want to combine them into one file for simplicity, but I will lose points. I've included my code so far. I'm not looking for a "fix-it" solution, I just want to figure out why it's not working. ANY help is appreciated, since my instructor isn't of much assistance Thank you kindly!
MAIN FILE:
import java.util.Scanner;
class Fruit1 {
static Scanner console = new Scanner(System.in);
public static void main(String args[]) {
String color;
String taste;
}
public Fruit1() {
// generic constructor
color = "red";
taste = "yum";
}
public Fruit1(String aColor, String aTaste) {
// constructor with parameters
color = aColor;
taste = aTaste;
}
public Fruit1(String bColor, String bTaste) {
color = bColor;
taste = bTaste;
}
String getTaste() {
return taste;
}
String getColor() {
// Accessor method
return color;
}
}
TEST FILE:
import java.util.*;
public class Fruit1Test {
static Scanner console = new Scanner(System.in);
public static void main(String args[]){
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
Fruit1 l = new Fruit1("yellow", "tart/sour");
a.taste();
a.color();
l.taste();
l.color();
System.out.println("Your apple is " + a.color + "in color and has a " + a.taste + " taste. ");
System.out.println("Your lemon is " + l.color + "in color and has a " + l.taste + " taste. ");
System.out.println();
}
}
a.taste(); will try to find method taste(); in your main file i.e. in Fruit1.java file. However as same is not found, it will throw error at compile time only that Method taste() is not found...
All below 4 statements will FAIL as those are not present...
a.taste();
a.color();
l.taste();
l.color();
As you are creating object of class by using below statement, already values to taste and color by use of constructor public Fruit1(String aColor, String aTaste){.
Fruit1 a = new Fruit1("pinkish-red", "sweet-tart");
I believe you now want to print the values of color and taste. To print those use getter methods that you have (getColor() & getTaste())
System.out.println("Your apple is " + a.getColor() + " in color and has a " + a.getTaste() + " taste. ");
System.out.println("Your Lemon is " + l.getColor() + " in color and has a " + l.getTaste() + " taste. ");
Note
You don't need to write public Fruit1(String bColor, String bTaste){ again as you have already defined above that....
Also your below statement should be before constructor and out of psvm
String color;
String taste;
Let me know if you are unclear...
Good Luck
You never declare the fields color or taste for the object Fruit1. Instead, you created the variables in the main method.
I suggest you read some basic tutorials on Java to get the hang of things. (Oracle also provides more advanced tutorials.)
I noticed in Fruit1, you are declaring the member variables in function main(). From the looks of it, Fruit1Test should have a main() fxn but Fruit1 should not. Take out those member variables out of main() and get rid of main() in Fruit1 (put it under the 'console' variable).
I also noticed that you have 2 constructors that both take in Strings. The compiler will probably complain about that too. I don't have a compiler in front of me but that's what I can tell just from looking.
For your first problem, it seems you're misunderstanding how to declare instance fields. You're creating them inside the main function, when you should create them directly inside the class.
For your second problem, see Fahim Parkar's comment, if it applies to your case. BTW it's a good practice to always have only one class/interface/enum per file, and have the file with the same name of the class (this second part may be mandatory in Java, I don't remember for sure - it applies to public classes, but I dunno if it also applies for "default, package protected" ones).
If they're named correctly, OTOH, maybe the error is because your "main" file didn't compile, so the "test" one didn't find it...
P.S. I just noticed you have two constructors with the same signature (number of parameters and same parameter types). You must remove one.
my Question is, is it possible to print out specific information from a class that provides no toString() method in JAVA?
There's the rub: We provide a logger for our application (using aspectJ) which prints out the specific arguments, that were given. For example:
public void addGroupMembers(Group group, String doneBy, DataListModel<User> users) {
doSomething()
}
And our Logger prints the following:
addGroupMembers called with given arguments:
Group = [id = ..... and so on]
username
DataListModel$1231 <-
We have to use the DataListModel-Class, because we're working with JSF in the background. But, as you can see, this class doesn't provide a toString method.
Our logger is written by ourself, so we can adapt that. Is it possible to simulate a toString method like: If the class doesn't provide a toString, catch all their fields, and print them?
Or is there any other way?
Thanks in advance for your help.
Greetings, Thunderhook
You could make use of ReflectionToStringBuilder. Something like:
if (object.toString().endsWith("#" + Integer.toHexString(object.hashCode())) {
// default toString()...
return ReflectionToStringBuilder.toString(object);
}
else {
return object.toString();
}
I've done this a few times using reflection. I had a generic method that was essentially dumpObject that iterated through the fields and put them to a string. This works great, but be sure to consider performance if you're calling this often - it might be better to hard code the tostring. e.g.,
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
log.info(field.getName()
+ " - " + field.getType()
+ " - " + field.get(obj));
}