I have 2 java classes, one being color.java and the other being size.java. The color class has my SQL statement pulling from multiple tables and my result set. What I'm trying to do is pass in the itemno and description from color into size. Once I pass those values into size.java it will do additional logic and then come back to color.java to finish.
I've tried using something like this:
public void getValues(String color.rs.itemno, String color.rs.description){
return itemno;
return description;
}
I'm new to java so I may not be on the right track, but looking at other examples I think it goes something like the above.
Okay so there are a couple of things wrong with the above code:
Currently, you have what is known as a mutator method. This is a method which does not return a value. Instead this is used to perform operations within an object, usually passing several parameters through it. In order to return a value, you will make use of an accessor method. For this, you need to state the data type you wish to return.
Next, you have named your variables incorrectly. You may wish to look at this document for the naming conversions here: https://www.javatpoint.com/java-naming-conventions What you have created now, are temporary variables only accessible within that method.
Lastly, you cannot return more than one variable at once. The nearest path will be taken and then the code stops running from there. So in your case, you would only be returning itemno and then the code will stop.
Here is an example how the code should look like keeping the above in mind:
String itemDescription;
int itemNumber;
public void setItemNo(int in)
{
itemNumber = in;
}
public void setItemDescription(String id)
{
itemDescription = id;
}
public int getItemNo()
{
return itemNumber;
}
public String getItemDescription()
{
return itemDescription;
}
I would however recommend making use of a constructor to set these values in the beginning:
public ClassName(int in, String id)
{
itemNumber = in;
itemDescription = id;
}
you need to collect all values from a result set in a container, array or arraylist or other, loop through them and then pass whatever you need to your function. Seen here
(String color.rs.itemno, String color.rs.description)
can should be changed to
(String itemno, String description)
Related
I created a class and made 57 objects from it, each one has specific ID number.
Can I create a method which returns an object using an ID as the argument?
For example, assume the name of my class is Things and I made two object from it called apple and dog, they have IDs 1 and 2.
Things.java:
class Things {
private String name;
private int ID;
public Things(String name, int ID) {
this.name = name;
this.ID = ID;
}
}
Main.java:
class Main {
public static void main(String[] args) {
Things apple = new Things("apple", 1);
Things dog = new Things("dog", 2);
}
}
in this example I want to create a method in class "Things" which returns object apple if I use 1 as argument and object dog if I use 2 .
You cannot identify objects by a particular property unless you store it in a special repository
You can create a ThingRepository and can get specific Things by the id.
public class ThingRepository {
private Map<Integer, Things> thingsRepository = new HashMap<>();
public void addThing(int id, Things things) {
thingsRepository.put(id, things);
}
public Things getThingById(int id) {
return thingsRepository.get(id); //Can return null if not present
}
}
The addThing method need not explicitly take the id. If you add a getter to Things, then it can be simplified to
public void addThing(Things things) {
thingsRepository.put(things.getId(), things);
}
Couple of problems you need to address:
Each created Things object has to be added to this somehow (either the caller needs to add or there must be some other wrapper/factory that must do this).
Once a Things is not needed, it must be removed from the above map, else it can lead to memory leak.
Btw, shouldn't Things be named as just a Thing?
There are two aspects here:
you need some sort of data structure that remembers about created objects, and allows you to access them by id, for example a simple Map<Integer, Things>. Each time you create a new Things (should better be called Thing, shouldn't it?!), you go thatMap.put(newId, newThing).
if you want that data to "survive", you would have to somehow persist it (like writing data to a file, database, ...)
If you use Intellij for example press: alt + insert and choose getters/setter.
If not just write your own getters/setter ;).
Like here: https://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
But basically if you want to look for Thing with particular Id you need to store somewhere them for example in ArrayList, then iterate through it and if your find element with that Id just return it.
1) Create new ArrayList
2) Iterate through
3) If you find Thing with Id you want, return it.
I have a server, from which i get the values that i need(name, date, city, picture_url). To get them are in getValues class. I'm using Json.
All the values are saved in an ArrayList called array. I would use them in multiple classes. I would like to call the array in FragmentB. This is the code for the ArrayList
private ArrayList<String> array;
`array = new ArrayList<String>();
array.add(finalresult.getString("picture"));
array.add(finalresult.getString("name"));
array.add(finalresult.getString("date"));
array.add(finalresult.getString("city"));`
Then i thought i needed some kind of function, so it can be called, from other classes. I wanted to name the function, then arguments are numbers, so you can select which element you want, then you just return the object you wanted.
public ArrayList<String> getEvent(int pos)
{
return array.get(pos);
}
But here i get an error:
Required: java.util.ArrayList <java.lang.String>
Found: java.lang.String
In Fragment, i want the specific element of the array, and save it in one string, so i can call it later.
Something like this:
public class FragmentB extends android.support.v4.app.ListFragment{
private GetEvents getEvents = new GetEvents();
private String picture1, name1, city1, date1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
picture1 = getEvents.getArray(0);
name1 = getEvents.getArray(1);
city1 = getEvents.getArray(2);
date1 = getEvents.getArray(3);
}
}
I know that this is wrong. What is the correct way to pass the elements, and then call them in the fragment?
Change
public ArrayList<String> getEvent(int pos)
{
return array.get(pos);
}
to:
public String getEvent(int pos)
{
return array.get(pos);
}
But I think you should consider passing info to your fragments via arguments
For the error, it is just that getEvent(int pos) should return a String and not a List<String>.
If (name, city, date, picture) is an object of your application model (I understand that these are used in several places), you may take advantage to create a simple pojo class to hold these infos, e.g.
public class Event {
String name, city, url;
Date date;
// +constructor
// +getters
}
Then you can store, pass as parameter, filter, sort Events and access properties with specific methods without ambiguity.
Actually storing values with different meaning in an array is bad practice: an array should contain objects of the same nature, e.g. a list of Event, a list of city, etc. Think of what will happen if the order in the array changes. Does it make sense to have city at position 0 and name at 1?
This question already has answers here:
How to avoid constructor code redundancy in Java?
(4 answers)
Closed 9 years ago.
Hi I am just learning about constructor chaining in Java and had some questions...
First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.
In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?
import java.util.*;
class Employee
{
private String name;
private double salary;
public Employee()
{
this("James Bond", 34000);
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public static void main(String[] args)
{
Employee a = new Employee();
}
}
Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.
static int numOfExamples = 0;
public Example(String name, int num)
{
this.name = name;
this.num = num;
numOfExamples++;
System.out.println("Constructor called.");
Log.info("Constructor called");
}
public Example()
{
this("James Bond",3);
}
That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.
Chaining constructors like this is useful to avoid repeating code, and helps with maintainability:
public MyClass(int x, double y, String z) {
// set fields
}
public MyClass() { // i.e. a constructor that uses default values
this(42, 4.2, "hello world"); // x is 42, y is 4.2, and z is "hello world"
}
If we didn't use the chain, and wanted to change how the x argument (for example) is processed when constructing an instance of MyClass, we would have to change code in both constructors. With the chain, we only need to change one of them.
1) As others have said, it's for code maintenance, basically the idea is that you only write one piece of code once, which means you only need to edit it once, there is no risk of overlooking something when editing your methods and the two accidentally becoming different.
Personally I tend to use this differently than in your example. Like so:
Employee() {
setupStuff();
}
Employee(String name) {
this();
this.setName(name);
}
This is a nice way of doing things, because potentially your setter can be way more complicated than just setting a member in the class. So basically what this does is puts calling the empty constructor and then a setter into a single method, making it much easier for anyone using the class.
2) The constructor being called doesnt't create a different object at all, it creates this object. Note that there is no new keyword used. Basically you're just calling a different method inside your constructor, except that method happens to also be a constructor.
Every time you want to allow constructing an object wit default values, and also want to allow creating the same object with non-default values. Let's imagine a DateTime class. You could want to initialize it with the current time by default, or with a specific time. Imagine a Car class. You could imagine constructing it with Black as the default color, or with a specific color. This kind of situation is very common. See java.util.ArrayList or java.util.Locale, for concrete examples.
It's stored in the name field. So you access it, from the object itself, with this.name (this being optional, just as in the getName() method).
How do I access this new "James Bond" object for future use?
Because you saved the values of name and salary as fields of your employee class, then inside the employee class you can use those fields, and outside your employee class you can use the getter/setter methos of your employee class
I've received a working code (in Java, 1.7) that does the following:
load an array of strings (a list of blood test names) from a file into a string array member (using Properties and FileInputStream). The file can change the strings but the meaning stays the same (for example: a test can be called "abc" and in another run it is called "zzz"). I've got an enum class that enumerates the test names. The enum strings aren't the same as the inputted strings (since the latter can change).
file bloodtest.names contains:
bloodTestNames=abc;def;123;
code:
public enum BloodTestNames {
AAA,BBB,CCC;
}
Properties props = new Properties();
FileInputStream fis = new FileInputStream("bloodtest.names");
props.load(fis);
String testName[]=props.getProperty("bloodTestNames").toString().split(";");
Now to the questions:
Question 1:
I need to return the string that was set in the file when I know the test name (for instance: return "def" for value BBB). What's the best of doing that?
the best way I've come up with is:
return testName[BloodTestNames.BBB.ordinal()]
Question 2: if BBB is not known in compile time - how do I accomplish the same target?
Three points:
* I'm a veteran at C but a newbie with Java. Any Do's and Don't are welcome. Assume my Java knowledge is zero.
* I don't total re-factoring is that's what's needed here.
* I've probably forgot to mention important details, please ask and I'll feel the missing gaps
I'll first assume you do need enum constants for modeling this use-case because you have some sort of specific code to be executed for each kind of blood test (otherwise, a simple set of strings would be enough and more flexible, since you don't need to know the number of tests upfront or care about their names).
Q1: Since Java enums are a little more than a sequence of values, you can make full use of their object oriented nature.
public enum BloodTest {
AAA, BBB, CCC;
private static String[] names;
public static void setNames(String[] names) {
if (BloodTest.names != null)
throw new IllegalStateException("You can only set the names once");
if (names.length != values().length)
throw new IllegalArgumentException("Wrong number of names");
BloodTest.names = names;
}
#Override
public String toString() {
return names[ordinal()];
}
}
Now all you need to do is to initialize your enum by calling BloodTest.setNames(namesFromConfiguration) and then you can get the string representation of each constant by calling the standard toString() method on it: BloodTest.BBB.toString().
Since the initial assumption was that you have some specific logic for each of the test types, I would suggest that logic (as well as the required properties) will also be encapsulated in the enum itself or the enum constants; e.g.:
public enum BloodTest {
AAA(10) {
#Override
public boolean isRequired(MedicalRecord medicalRecord) {
return medicalRecord.includes("someDisease");
}
},
BBB(15) {
#Override
public boolean isRequired(MedicalRecord medicalRecord) {
return ! medicalRecord.hasTakenBloodTestsLately();
}
},
CCC(20) { // ... also implements the abstract method and so on
private final int threshold;
private BloodTest(int threshold) {
this.threshold = threshold;
}
public boolean hasPassed(int value) {
return value <= threshold;
}
public abstract boolean isRequired(MedicalRecord medicalRecord);
// ... same as above
}
Now, once you get a reference to some BloodTest, you can check whether that specific test passed by invoking the corresponding method without switching and having the logic spread around the client code:
BloodTest bloodTest = BloodTest.valueOf(someString); // someString can be "AAA", "BBB" or "CCC"
// no matter which constant this is, you use it as an object and rely on polymorphism
if (bloodTest.hasPassed(someValue)) { // ... do something
Q2: Your question 2 kind of "questions" my initial assumption regarding your actual need for an enum. If there's a chance you'll need to dynamically handle blood tests that you don't know about yet, then you can't use an enum.
In other words, if your code does not have any switch or if/else if blocks to handle each blood test, an enum is a really bad choice for your use case.
However, if it does, than I'd recommend refactoring the code to include the logic in the enum itself as in the above example, rather than in switch/if blocks; moreover, if your switch has a default case (or your if has a final else block), this can still be modeled in the enum itself, for instance by adding a DEFAULT constant as a fallback.
Make the whole thing settings driven: Add a statuc method to load in settings of what string maps to what enum and add a factory method that uses these settings:
public enum BloodTestNames {
AAA,BBB,CCC;
private static Map<String, BloodTestNames> map = new HashMap<String, BloodTestNames>();
public static void addAlias(String alias, String name) {
map.put(alias, valueOf(name));
}
public static BloodTestNames getByAluas(String alias) {
if (map.containsKey(alias))
return map.get(alias);
// own name assumed to be mapped
return valueOf(alias);
}
}
On startup, repeatedly call BloodTestNames.addAlias() based on some settings file to load the mappings.
When you're reading the saved file, use BloodTestNames.getByAlias() to return the enum for a given string value.
You would do well to name your class in the singular, and drop "Name", ie BloodTest - name the class for what each enum is (all enums have a "name" which is the coded instance name).
A short extract from one of my enum class :
public enum TypesStructurelsE {
SOURCE("SRC"),
COLONNE("COL");
private String code;
TypesStructurelsE(final String code1) {
code = code1;
}
/** #return String */
public String getCode() {
return code;
}
public void setCode(final String newCode) {
code = newCode;
}
}
. . In other class
if(TypesStructurelsE.SOURCE.getCode().equal(testName[i])){ // can be "COL" or "SRC"
//
;
}
... changing value :
TypesStructurelsE.SOURCE.setCode("SOURCE_NEW");
So, if your properties file change, you have just to compile with the new symbole (SRC --> SOURCE) no more
fairly new to this language. Long time lurker, first time question asker.
In my program, I load a bunch of strings from a text file and then pass all of that information inside of a String array to a program that takes the data point by point (it comes in a reliable pattern) and assigns it to variables inside a class.
I use this loop to create the objects.
Gladiator[] gladiator = new Gladiator[(match.contestants)];
for ( int a = 0; a < match.contestants; a++) {
gladiator[a] = new Gladiator();
gladiator[a].populategladiators(parsedInfo,a);
}
Gladiator class full of public final variables which are defined in the method populategladiators. The syntax is as follows:
this.name = parsedInfo[0+mod][0];
this.culture = parsedInfo[1+mod][0];
this.background = parsedInfo[2+mod][0];
etc.
At the moment, I only load two gladiators and it seems like maybe both are being set at once with both pass throughs? Anyone have any thoughts on this?
Also, in another method in class Gladiator, should I be able to call this.name and be okay to get data about the object I specified when calling the method?
Edit: Trying to make the code look right. Giving up since there isn't much.
2nd Edit: Example of variable declaration in gladiator class:
public static String name;
public static String culture;
public static String background;
I had my variables set as static, thus it wasn't allowing me to set individual variables for the objects. I just didn't understand what the static keyword meant.