Changing Value Of Object Instance
Jul 13, 2014
I have been working on a program that is meant to use a class' instructions in a program to add a value to a variable, save it, and present it. This is my class
public class Car
{
//FIELDS
private int yearModel;
private String make;
private int speed;
//METHODS
public Car(int carYearModel, String carMake)
[Code] .....
Whenever I call the accelerate method, a value of 5 is to be added to the speed variable. But whenever I call accelerate, it doesn't increase! I just don't understand why not. I've tried different renditions of adding 5 to speed and it doesn't quite work. I don't get any errors when I compile, just runtime, when it doesn't add 5 to speed.
View Replies
ADVERTISEMENT
Feb 12, 2015
I want to make a private method that will change the value of a instance variable like this:
String bla = "bla bla bla";
private void changeString (String x) { x = "eee";}
changeString(bla);
Now value of the variable bla should be "eee" but its not, it is stil "bla bla bla".
View Replies
View Related
Apr 7, 2014
So far in my assignment I have successfully opened a text file. However I am required to do more:
1) As each line of text (containing names and ages) is read a new Runner object is created with its instance variables set thus: ! (Runner class already created )!
- name : set directly set from the value in the file
- agaGroup : can be worked out from the given ages:
< 18 should be 'junior'
> 55 should be 'senior'
the rest should be 'standard'
2) the instance of Runner should be added to the list referenced by the instance variable runners.
I have used if statements to create the junior list, however I do not see the full list of names and ages in the variable runners as I am requested to.
I am sure there is a for loop involved somewhere but I do not know how to:
a) use the for loop in my method
add a new Runner object with the variable mentioned.
I include the code I have done so far as a file - p.s I use Bluej.
public class MarathonAdmin
{
// instance variables
private String runners;
private String age;
[Code] ....
View Replies
View Related
Feb 5, 2015
Let's pretend I'm working on an RPG. Like in all RPGs, there are items found all throughout the imaginary world. Each player and NPC can obtain an item. My question will concern those items.
In other words, I'd like to use instances of a class in multiple places of the code. Each instance will have its own, individual values of instance variables, with one obvious exception: itemQuantity should have a different value in playerInventory, npcInventory, etc. Also, I'd like a list of all items that can be found in the game. This list doesn't need itemQuantity at all.
class Items {
String itemName;
float itemWeight;
int itemQuantity;
[Code] ....
The question is: should I really make itemQuantity an instance variable of the Item class? It seems as though for each copy of the Item class I should create a separate copy with different value of itemQuantity, but that's not very efficient. Where is the error in my logic?
What's important is that there may be plenty items in a game and a player may be given power to create new items during the course of the game.
View Replies
View Related
Oct 26, 2014
I can't figure out where to create the StringHandler object. My code should take a string as input, then create StringHandler object ord with the string input. This should repeat until cancel is pressed, then ord should be sent to the Utskrift-method (a print method).
If I do like this, null is also sent to Utskrift. I dont want that to happen.
If I put StringHandler last in the loop ord can not be resolved.
String text = "";
while (text != null){
text = showInputDialog(null, "Enter text:");
StringHandler ord = new StringHandler(text);
if (text == null){
[Utskrift(ord.getNumber(), ord.getString(), ord.getWords());
break;
}
}
View Replies
View Related
Jun 30, 2014
so, i was reading my java book and learning about objects and methods and it starts talking about Encapsulation and mentions that it's good practice to set instance variables as private and instead of accessing the instance variables directly, we should create a set method and get method to get and set the stuff we want to pass to the class containing the object...
for example, in this class, we're passing the integer 70 for object dog one and integer 8 for object dog two for the dog class... and these these 2 integers are sent to the setsize method so we're not accessing instance variable size directly.
i dont quite get it though....if we the programmer are the one deciding what size the integer is for the dog, and the setsize method takes the one.setSize(70) or (8) and puts them in setsize(int s) as s... but only to copy that integer stored in s back to private int size.... why do we even need to bother with making these two extra methods such as setSize, getSize?
in the book it says that... well what if the code gets into the wrong hand and someone writes something like one.setSize(0) then you would get a dog with size 0 which is essentially illogical. but then again, i'm the programmer, and i am the person who writes the code and passing the right integer.The reason for public and private... that part i understand... i can see why if a variable's data can get changed amidst the code during calculations and you dont want it to directly change the original variable and have it mess up the code, but this code from the book just a bad example of demonstrating the reason? since we manually pass the information ourselves and passing it to method setSize... and all setSize does is stores it in another integer, only to copy it right away to size (which is the original private variable we were tryign to protect?
Any simple code to demonstrate how the code might end up changing an instance variable and why we would want to protect it by using private?
class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;
[code]...
View Replies
View Related
Mar 7, 2015
I am currently trying to use Junit to test a whole bunch of stuff. I almost have full line coverage but I am getting hung up on testing an if statement that consists of whether or not an object is an instance of another class. This class happens to be an interface, and even the object is an interface. Weird I know but I just want to know how to get into that if statement. I realize testing interfaces might be a waste of time but I still really want to know how. Here is an example of what I am trying to test:
Java Code:
if(x instance of y){ //where x and y are both interface objects
doSomething();
} mh_sh_highlight_all('java');
View Replies
View Related
Aug 9, 2014
Essentially, the code I want is:
public void randomCreate(ParentObject obj){
int x = random(0-4); //pseudo
int y = random(0-4); //pseudo
create new ParentObj(x,y);
}
ParentObject is actually abstract, so you would only ever pass one of its children objects to it, and a child object of that type would be created. It seems like there should be a way to pass a type, rather than an object, and then create an instance later down, but I don't know if that is actually possible, or if it is poor programming style.
View Replies
View Related
Mar 30, 2014
what have I done wrong n the following code? I'm trying to create a new instance carte of object Carti using the constructor and then to insert a row into a table created with SQL.The error I'm getting is:
Exception in thread "main" java.lang.NullPointerException
at Carti.Carti.InsertCarti(Carti.java:103)
at Main.main(Main.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 28 seconds)
The line Main.main(Main.java:37) is when I try to insert the row.
The line Carti.Carti.InsertCarti(Carti.java:103) is when I do the
PreparedStatement st = conn.prepareStatement("insert into Carti (Id,titlu"
+ ", descriere, autor, editie, anPublicare) values (?,?,?,?,?,?)");
Here is the code (Main and Carti Classes)
import Carti.Carti;
import Imprumut_Carti.Imprumut_Carti;
import Membrii.Membrii;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import java.sql.SQLException;
import java.text.DateFormat;
[code]....
View Replies
View Related
May 5, 2014
Whenever i perform any operation in my application Live Bytes of a particular Instance of a class increases by 1000.Although i perform the same operation everytime it always increases by 100 or 1000.Is this a memory leak or does these instances increase everytime we perform an operation.
View Replies
View Related
Mar 7, 2014
I've Parent and child(extends Parent) class To initialize the constructors, I'm injecting from google.juice#injector. Let me show the code,
Parent.class
public class Parent{
private Animal animal;
@inject
Parent(Animal animal){
this.animal = animal;
[code].....
When I do this, ClassCastException is happening. Why is it so? Is there any way to convert instance of parent to child instance.
View Replies
View Related
Mar 28, 2014
Create an equals method that takes an object reference and returns true if the given object equals this object.
Hint: You'll need 'instanceof' and cast to a (Geocache)
So far I have:
public boolean equals(Object O){
if(O instanceof Geocache){
Geocache j=(Geocache) O;
if (this.equals(j)) //I know this is wrong... but I can't figure it out
return true;
}
else return false;
}
I think I have it correct up to the casting but I don't understand what I'm suppose to do with the this.equals(). Also I'm getting an error that I'm not returning a boolean... I get this all the time in other problems. I don't get why since I have to instances of returning booleans in this. "returns true if the given object equals this object" makes no sense to me. I assume the given object, in my case, is 'O'. What is 'this' object referring to?
View Replies
View Related
Jan 16, 2015
in a set of instructions they keep referring to instance versions of things I've heard of before ie "private instance array of String references" (wtf is a string reference?) or "instance string variable" so what does all this mean?
View Replies
View Related
Sep 18, 2014
.I was reading head first java book and saw a barbell question on page no. 280,question-"what if you want to write a class in such a way that only one instance of it can be created,and anyone who wants to use an instance of the class will always use that one,single instance?"
View Replies
View Related
Apr 7, 2013
In the following example, I compute new_amount_d in 2 different ways and I get 2 different values although it should be the same in theory.
Is there a way to get the same value with BigDecimal for instance?
public class num004
{
public static void main(String[] args) {
double amount_d = 1000;
double interest_rate_d = 0.03;
[Code] ....
View Replies
View Related
Feb 23, 2015
I am working on a project and it asks me to "Provide appropriate names and data types for each of the instance variables. Maintain two GVdie objects" under class fields. I am unsure as to what is being asked when asking for two objects as instance variables and how I would write that...
View Replies
View Related
Feb 23, 2015
I have a method that accepts JSONArray as parameter and returns the values of it as ArrayList Object. My question which of these ways is appropriate in populating the ArrayList object this method populates the arraylist upon creation of object (I don't know what the right term to use, but as netbeans IDE suggest, JSONArray object should be final since it was used in inner class.).
private List<String> getStringList(final JSONArray jsonArr) {
return new ArrayList<String>() {
{
try {
for (int i = 0; i < jsonArr.length(); i++) {
add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
};
}
this second method is the usual way of populating collection
private List<String> getStringList(JSONArray jsonArr) {
List<String> strList = new ArrayList<String>();
try {
for (int i = 0; i < jsonArr.length(); i++) {
strList.add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
What are the advantages and disadvantages between the two? like which is faster? or which consumed larger memory?
View Replies
View Related
Sep 25, 2013
Can I declare a class as
public static final?
Because I can declare a variable as public static final pi=3.14;
View Replies
View Related
Sep 26, 2014
I want to create a new instance of a Java model class for each new request coming to a servlet.
How to do that without doing that in doGet() or doPost().
View Replies
View Related
Oct 24, 2014
I have the following 2 classes:
class Address {
private int a;
public void set_a(int a) {
this.a = a;
}
}
class Person {
private Address address;
}
How do i access the method set_a() (through the "address" in Person) from another class which contains main() ?
View Replies
View Related
May 5, 2014
I'm just wondering why variables in interface can't be instance scope?
interface Test{
int a;
}
And then
Test test = new TestImpl();
test.a=13;
Yes, it violates OO, but I don't see why this is not possible? Since interface is not an implementation, therefore it can;t have any instance scope variable. I can't find the correlation of interface being abstract and being able to hold instance scope variable. There's gotta be another reason. I'm just curious about any programmatic limitation, not deliberate design constraint. the example of programmatic limitation is like when Java forbids multiple inheritance since when different parents have the exact same method, then the child will have trouble determining which method to run at runtime.
View Replies
View Related
Jan 25, 2014
I have 1 textfield and 1 button on a JFrame and having 10 such frames stored in ArrayList al and getting the JFrame instance from traversing the ArrayList at execution time ,So is there a way to access textfield using JFrame instance or i have to name the textfield diffrently 10 times for each frame .
View Replies
View Related
May 6, 2015
Alright, I have a JavaFX gui that is creating a new instance of data calculation to graph in a chart; however, the data is not updating each time the Platform.runLater() feature executes. Each time an event occurs, a new instance with the same variable name occurs. I use to get methods to retrieve the data I want, so shouldn't the values update each time the new instance is created? This is a very condensed version of what happens with the event, but this is what is not working correctly.
Event:
solarPlot = new SolarTracker();
solarPlot.getElevation();
solarPlot.getAzimuth();
Class constructor :
public SolarTracker() {
[Code] .....
View Replies
View Related
Jul 26, 2014
I am working with a JFormattedTextField. After adding the text of the FormattedTextField to an LinkedList i want to read it out and sum it up. So I have a problem to convert the String to and integer...
Example:
23.00 - to 23.00
+ 11.00 - to 11.00
--> 34.00
I have tried it with splitting the string but it didn't work. How to do it?
View Replies
View Related
May 23, 2014
Is there anything wrong on my code?
import java.util.*;
public class Card
{
private String description;
private String suit;
private int value;
private static final String [] cardName {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Jace","Queen","King","Joker"};
[Code]...
View Replies
View Related
Sep 16, 2014
Is there anyway to iterate an enum type without an instance. As some context, consider the following code:
Java Code: public interface GenericChecker
{
public bool isValid(String str);
} mh_sh_highlight_all('java'); Java Code: public class EnumChecker<T extends Enum<T> > extends GenericChecker
{
private Class<T> enumType; //No instance
[code]....
toString method of the enum types has been overridden so that it returns the name assigned to the enum rather than the enum name itself. For example an enum might be SOME_ENUM("Assigned name"), therefore toString returns "Assigned name" rather than "SOME_ENUM". The idea is that a field from a table can be handed to the isValid(String) function on the GenericChecker base, and the derived class will then check to see if the field matches valid data as far as it is concerned.Thus, I can create a whole bunch of checkers easliy:
Java Code: GenericChecker checker1 = EnumChecker<EnumType1>();
GenericChecker checker2 = EnumChecker<EnumType2>();
GenericChecker checker3 = EnumChecker<EnumType3>();
GenericChecker checker4 = SomeOtherChecker(); mh_sh_highlight_all('java');
The problem is, if I use the EnumChecker then the expression "enumType.getEnumConstants()" in the isValid function blows up because enumType is null.
View Replies
View Related