call existing class by name in String variable - java

Let's say I have a
public class things {
String name = new string;
int nr = new nr;
//constructor etc
}
Now let's assume there are already a bunch of instances initialized. let's call them thingA, thingB, thingC (I will need them to be more later...)
I'm having a JFrame where the User can Input a text and the input shall be one of the classes so he could type "thingB", "thingD", ... "thingN"
within an actionPerformed I now want to:
String s = jLabel_1.getText();
and then do sth like.
System.out.println("" + s.nr)
Obviously, that doesn't work since s is a string only containing the value entered in the text-label, so what I wanna do is tell Java that the object's name I'm trying to use is the one saved in 's'. I really tried to look it up but I couldn't find anything except a
Class.forName(String...) option which didn't really work either, respectively I didn't know how to use it.

Related

Empty array object creation in Java

I am trying to learn some foundational ways to manipulate certain aspects of coding that stray away from single use and make something more "dynamic" that can kind of build itself on the fly.
For example of what I would like to accomplish, which I believe would consist of using some type of empty array of an object and a loop. I just don't know how to write it.
Lets keep it basic and say I have a Person Class.
public class Person
{
String name;
String age;
}
So in my TestDrive I would just get a simple user input to gather information on that person.
Such as...
import javax.swing.JOptionPane;
public class PersonTestDrive
{
public static void main(String[] args)
{
String name;
String age;
name = JOptionPane.showInputDialog(null, "Enter your name");
age = JOptionPane.showInputDialog(null, "Enter your age");
Person human = new Person();
human.name = name;
human.age = age;
JOptionPane.showInputDialog(null, "Would you like add another entry?");
/* At this point it would loop if the user wanted to add another entry.
I would just wrap it all in while loop that just checked if the user said yes or no.
However, if they do choose to add another entry
"IF" a human object already existed it would create a
new human2 object, and then human3, etc. */
}
}
It sounds that all you need is a collection of objects, such as ArrayList<Person>.
"human" is a name of your variable, and at compile time you don't know how many other variables there can be so you cannot refer to them in the code using "human2", "human3" and so on. You can create these variables, but they may be nulls and your input will also be limited to how many variables you have. Another problem would be keeping track of what variable to assign to next.
With List<Person> list you can do list.get(2) to get third object (it will thrown an exception if there are few than 3) or list.size() to check how many objects were created so far.
Here is some more information about Java collections: http://docs.oracle.com/javase/tutorial/collections/

java get value from JTextField and set it as BigInteger

I have two classes in a package: firstClass and secondClass.
I created a textfield in firstClass, let's assume it's txtStringNumber.
I created a method in firstClass to get txtStringNumber value, like this:
public String getStrNumber(){
String strNumber = txtStringNumber.getText();
return strNumber;
}
I must pass it to secondClass as String and put the strNumber as BigInteger value.
In second class I created a method to get value of txtStringNumber from firstClass, like tis:
public static String theNumbers(){
firstClass f = new firstClass();
return f.getStrNumber();
}
public static String strAllNumbers = theNumbers();
When I print strAllNumbers in secondClass, it prints the correct value. Then I add this:
public static BigInteger bigAllNumbers = new BigInteger(strAllNumbers);
In my mind, it should works. But in real, it doesn't. Error occurs.
So I check the error, there said:
throw new NumberFormatException("Zero length BigInteger");
I guess BigInteger accept strAllNumbers as empty.
But just like I already said, when I print strAllNumbers directly without set it to BigInteger, it returns the correct value.
What's wrong here and how can I fix this?
You're creating a firstClass object, f, and getting a String from its textfield before anybody ever has a chance to enter text in it. So no surprise that it's empty.
Solution: Don't do this! Only get the text after something that makes sense has been entered.
I'm guessing that you have two firstClass objects, one displayed, and a second one created in this method, and are guilty of magical thinking that changes to the displayed object will be reflected in the newly created one, but that's not how programming works. Instead pass a valid reference of the displayed object to the other object that needs it.
You're creating a new instance of firstClass in the theNumbers method (firstClass f = new firstClass();), it's very unlikely the the value of the text field has been set to anything useful (especially by the user)
You either need to supply a means of firstClass to pass the value from the text field to secondClass, probably via a setter of some kind (this is classic producer-consumer pattern) or set up a mechanism for firstClass to notify secondClass when the value changes and then have secondClass retrieve that value (this is a class observer pattern).
In any case, you should not be creating a new instance of these classes, you need to create them and then pass these instance to which ever one is going to act as the controller...

How to name an array with a variable in java?

I am trying to make a calendar in Java that will store events such as doctors appointment, etc. I plan on storing these events as String arrays, containing the name of the event, the location of the event, and the time of the event. In order to generate new events, however, the arrays need to have unique names which I want to be the date they occur on. To do this, I planned on making a method that would take a new name for the array as a variable and then use that variable as the name of the array (as below):
public static void addInformation(String eventLabel) {
String eventName = JOptionPane.showInputDialog(null,"What yould you like the event to be called?");
String eventLocation = JOptionPane.showInputDialog(null, "Where will this event take place?");
String eventTime = JOptionPane.showInputDialog(null, "What time will this event take place? Input as: \"hours:minutes\" using a 24 hour clock.");
String[] eventLabel = {eventName, eventLocation, eventTime};
events.add(newEvent);
}
When I try this, I get an error saying: eventLabel is already defined in addInformation(java.lang.String)
Is there any way to name an array with a variable using a parameter? Any help would be appreciated. Thanks in advance.
EDIT:
It seems you cannot have a variable variable name. Is there a way to create a unique array each time this method is called?
Use a HashMap. For each entry, set the key using the eventLabel parameter, and value as your array. This way, you will have a name for each of your "arrays" (which will be an entry in the HashMap, in this case).
Your method declaration has eventLabel as type String. You try to redefine it as String[]. Try String[] eventLabelArray.
Hot Licks is correct - you cannot do something like addInformation('Arr') and have eventLabel be named 'Arr' and call Arr[0]. Why do you need it to be variable?
What you are trying to do is like using a variable name to create a variable name, I am not sure if this can be done.
But Maps can be used to solve your problem.Maps will provide your exactly same functionality as you want
for example:
Map<String, Something> myMap = new HashMap<String, Something>();
String name = eventName + eventLocation + eventTime;
myMap.put(name, new something);
eventLabel is used as both a local variable in the method as well as a passed-in argument. Give the two different names and that should fix your problem.
You cannot use the same name as the variable passed (String eventLavel) to your function
public static void addInformation(String eventLabel){
String eventName = JOptionPane.showInputDialog(null,"What yould you like the event to be called?");
String eventLocation = JOptionPane.showInputDialog(null, "Where will this event take place?");
String eventTime = JOptionPane.showInputDialog(null, "What time will this event take place? Input as: \"hours:minutes\" using a 24 hour clock.");
String[] arr = {eventName, eventLocation, eventTime}; // some other name!
events.add(arr);
}
It's good you're thinking about things this way, but I think you're trying to solve a non-problem.
Is there a way to create a unique array each time this method is
called?
Yes, it happens for free - you don't have to do anything. Because the array is being created inside the method, a new one gets created every time. So as others have said, just use a different variable name (not eventLabel) and you're good to go.

Object in Object Array doesn't want to store my data

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.

When creating methods and passing objects as parameters, are they copied or referenced? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
see example below... need java.io library to run...
public class BlankClass extends ConsoleProgram {
public void run() {
while(true) {
setFont("London-24");
String name = readLine("Type a name: ");
fixName(name);
/* I know that the way this is written doesn't make sense and that println(fixName(name))
* is the right way. However, I thought that when objects then the method is using the object
* (in this case a string) and not a copy of it. In other words, it is referenced.
* So if it is referenced why isn't it printing out Steven when I give it STEVEN.
*/
//println(fixName(name); this is removed to show the question.
println(name);
}
}
private String fixName(String name) {
char first = name.charAt(0);
first = Character.toUpperCase(first);
name = name.substring(1);
name = first + name.toLowerCase();
return name;
}
}
Java always passes parameters by value - but in the case of classes/objects, the value that's passed is a reference, not an object itself.
What the type involved, the value of the argument expression is copied as the initial value of the parameter. Changes to the parameter variable itself are not seen by the caller, whereas changes to the object that the reference refers to will be seen.
For example, using StringBuilder (which is a mutable type):
public void foo(StringBuilder builder)
{
builder = new StringBuilder("Change to builder");
}
public void bar(StringBuilder builder)
{
builder.append(" - appended");
}
Now:
StringBuilder x = new StringBuilder("Original value");
foo(x);
System.out.println(x); // Still prints "Original value"
StringBuilder y = new StringBuilder("Original value 2");
bar(y);
System.out.println(y); // Prints "Original value 2 - appended"
Note that when I say "the value of the argument expression", that is never an object - it's either a primitive value, or a reference.
I like to think of an analogy with houses. Suppose you have a piece of paper (a variable) with directions to a house written on it. You call a method and use that variable as the argument - that creates a new piece of paper (the parameter) with the same directions on. If the method crosses out the original directions and replaces them with some other ones, that doesn't change the first piece of paper. On the other hand, if the method follows the directions and then paints the house red, then you would see that change if you followed the directions on the first piece of paper.
EDIT: To explain your original code... no objects are being copied, but the value of name in run is being copied into fixName. You're then changing the value of the parameter in fixName when you write this:
name = name.substring(1);
You're changing it again when you write:
name = first + name.toLowerCase();
Neither of these have changed the value of name in the calling code, which is still referring to the original string.
You're then returning the new string reference here:
return name;
but your calling code is completely ignoring it, because you've just written:
fixName(name);
One way to demonstrate what's happened is to use the return value in a new variable:
String fixedName = fixName(name);
Then you could print out name (which would show the original string) and fixedName (which would show the new one).
you pass a reference, so you work with the same string, BUT you return another string, because String in java is immutable - every operation (such as subString) produce new string and if you want to perform many operations on string (such as substring, replace etc.) use a StringBuffer or StringBuilder
This does not really answer your question, but you should avoid assigning parameters (like 'name' in this case), it can be handy at times but it is generally considered a bad practice because it often leads to unreadable and hard to maintain code.
In your case the variable is both a parameter and a local variable.
In Eclipse there is a warning you can activate for this in
Preferences->Java->Compiler->Errors/Warnings->Code style->Parameter assignment
I would recommend to set the parameter 'name' final in order to enforce this.
Return another String that is based on your 'name' String and name it properly.
The goal is that anyone reading your code should be able to quickly understand what is going on by elimination (the function is private, it is static, the parameter is final...). This excludes a lot of side effects.
Search for the concept of 'pure functions' on the web. Make the method static so the person reading your code knows that there are no side effects on the instance.
Here is the new version:
private static String fixName(final String name) {
final char firstCharOfName = Character.toUpperCase(name.charAt(0));
final String fixedName = firstCharOfName + name.substring(1).toLowerCase();
return fixedName;
}

Categories