Java bicycle and bicycle test - java

I have a problem to write my code. This is a code where I have to create an object class and run it using another class object.
The program is called bicycle and bicycletest.
I was given the bicycle program (its already been written) and all I need I write bicycletest to utilize the bicycle.
Now, the problem is, i have created 2 object, called NiceBicycle and CoolBicycle. I need to change my NiceBicycle name to "Kenny McCormick, but i cant do it. i keep getting error saying
"error: variable NiceBicycle might not have been initialized" for this line of command that i write.
// Change the owner's name to Kenny McCormick using setOwnerName
NiceBicycle.setOwnerName("Kenny McCormick");
what should i do?
anyway, here is the bicycle code, and bicycletest that i write based on the instructor command.
Thank you for your reply
bicycle.java
public class Bicycle
{
// Instance field
private String ownerName;
private int licenseNumber;
// Constructor
public Bicycle( String name, int license )
{
ownerName = name;
licenseNumber = license;
}
// Returns the name of this bicycle's owner
public String getOwnerName()
{
return ownerName;
}
// Assigns the name of this bicycle's owner
public void setOwnerName( String name )
{
ownerName = name;
}
// Returns the license number of this bicycle
public int getLicenseNumber()
{
return licenseNumber;
}
// Assigns the license number of this bicycle
public void setLicenseNumber( int license )
{
licenseNumber = license;
}
}
and here is bicycletest.java that i wrote.
public class BicycleTest
{
public static void main( String[] args )
{
// Create 1 Bicycle reference variable. For example: myBike
Bicycle NiceBicycle;
// Create 1 String reference variable for the owner's name
String name;
// Create 1 integer variable for license number
int licenceNumber;
// Assign your full name and a license number to the String and
// integer variables
name = "Boo Yeah";
int licenseNumber = 9972;
// Create a Bicycle object with the Bicycle class constructor
// Use the variables you created as arguments to the constructor
Bicycle CoolBicycle = new Bicycle( "Boo Yeah", 9972 );
// Output the owner's name and license number in printf statements
// using the object reference and the get methods.
// For example: bike.getOwnerName()
System.out.printf ("The CoolBicycle owner's name is %s\nThe license number is %d\n", CoolBicycle.getOwnerName(), CoolBicycle.getLicenseNumber());
// Change the owner's name to Kenny McCormick using setOwnerName
NiceBicycle.setOwnerName("Kenny McCormick");
// Output the owner's name and license number in printf statements
// using the Bicycle object reference variable and the get methods.
System.out.printf ("The NiceBicycle owner's name is %s\n", NiceBicycle.getOwnerName());
}
}

You need to instantiate Bicycle and assign it to NiceBicycle in your test by changing:
Bicycle NiceBicycle;
to:
Bicycle NiceBicycle = new Bicycle("", 0);
Then you can setOwnerName() on it:
NiceBicycle.setOwnerName("Kenny McCormick");
Also, note that Java conventions suggest that variable names start with lowercase letters, so NiceBicycle should really be niceBicycle if you want to follow Java conventions.

NiceBicycle hasn't been initialised (the bicycle object hasn't been created).
Try replacing
Bicycle NiceBicycle;
With
Bicycle NiceBicycle = new Bicycle("",0);

The compiler is being kind. You didn't set NiceBicycle before trying to use it. The variable is not set.
Also note that the Java convention is to always name variables starting with lower case, and classes starting with upper case. This is important because . is heavily overloaded, that is, it dues many different things.

you need to initalize your NiceBicycle object.
Bicycle NiceBicycle = new Bicycle( "Some value", 9972 );

Try something like this
Bicycle NiceBicycle = new Bicycle("User2", 0);
Then try to change the name of the owner

You are having just a reference to a Bicycle object
Bicycle NiceBicycle;
Therefore actual Bicycle instance haven't created yet in the memory.
Before you are setting the name you must create an actual instance first. Then try to set the name.
Bicycle NiceBicycle = new Bicycle(null, 0);
NiceBicycle.setOwnerName("Kenny McCormick");

Andy you have created the constructor for Bicycle class that will set the name of Owner and licenseNumber. Ever time you create an object you use new keyword. As it performs some operations i-e 1 it will call the default constructor or overloaded constructor according to values you gave 2 it allocates the memory. That is why when you create an object of class you use new keyword now you are getting error because you have not properly initialized the object to initialize it you will do it as Bicycle NiceBicycle = new Bicycle("",0); now to set values you will call its Setter and Getter methods like thisNiceBicycle.setOwnerName("SetName") now to get name you will call as string OwnerName = NiceBicycle.getOwnerName()

Related

Don't understand the link between constructor and object

I'm trying to learn java and and moving along OK but I ran across this example and I don't understand how "tommy" is passed from myPuppy to name. Can someone explain how that works? I don't understand how the 2 are linked.
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String [] args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
It's not passed from myPuppy to name. What happens is:
A new Puppy object is created when the new Puppy(...) expression is evaluated.
The constructor is called. Each parameter in the constructor (in this case, name) is replaced with the argument that is passed to new. In this case "tommy". So inside the constructor, the variable name now refers to the string tommy.
Then the new constructed object is assigned to the variable myPuppy.
You can think of the Constructor as a function having one parameter which is "name". In the body of this function, you have the console printing statement.
Once you call it in your main program, then a Puppy will be initialized with the name provided, which is "tommy" in here.
Once you have this object initialized, the name will be printed on the screen.
As the name already implies, a constructor constructs an object. An object is an instance on a class. In your case Puppy is the class you are creating an object of.
In Java a new object is created by the new keyword. You can think of the constructor being called like a function when you create a new object of a class.
In this case new Puppy("tommy") will pass the constructor a reference to the String "tommy" and will assign it to the variable name. The System.out.println(...) call will then be passed the reference to "tommy" and print it out on the console.

object oriented programming, constructor with parameters

So here is the code, and there are few lines I don't understand.
account acct = new account(); // making a new object named acct, type:account
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct); // new object created with parameters.
acct.addObserver(c1); // also not sure.
acct.addTransaction(100.00); // not sure....
This is Java. I'm not sure how parameters are passed to the constructor.
In java, the constructor is invoked when the object of the class is created using the new keyword. So to call the constructor with a certain parameter you just have to create an object with parameter as per your requirement example in your case.
class ConsoleAccountEvents {
Account account;
public ConsoleAccountEvents(Account account) {
this.account = account;
}
}
class Account {
}
So when you create object with
Account acct = new Account();
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct);
So here parameterized constructor will be called and this object will be assigned in instance variable of ConsoleAccountEvents class
Your ConsoleAccountEvents class must look like something like this-
class ConsoleAccountEvents {
Account accObject; // you have an object of 'Account' class as a member variable in this class
// other variables
public ConsoleAccountEvents() {
// body here
}
public ConsoleAccountEvents(Account accObject) {
this.accObject = accObject; // see below
// body here
}
// others
}
Doing this ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct);
You are calling the parametrized constructor which takes an Account object as parameter and generally initialize the accObject (object of Account class) in ConsoleAccountEvents with it.
Now, For acct.addObserver(c1);
In your Account class you must have a method addObserver that takes a ConsoleAccountEvents as parameter. like
void addObserver(ConsoleAccountEvents evOb) {
// body
}
PS: Please follow java naming conventions and other conventions, like capitalizing the first letter of name of a class etc.
And stackoverflow is not going to be of much help if you dont go through Java Language Tutorial. Good luck...!
I think what you may be looking for is how the new keyword works, but let me be thorough:
Some things to note about constructing objects in Java:
A constructor will be called every time you "request" a new Account().
A constructor can be defined to use parameters (and thus require arguments) of any type - both class types and primitive types (int, float, char, etc..)
If the constructor is called like new SomeClass(someObject), someObject is the argument passed to the constructor of SomeClass.
In the constructor of a class, parameters are defined with a type and a name as such:
class ConsoleAccountEvents{
Account account;
ConsoleAccountEvents(Account a){
account = a;
}
}
Here the parameter "a" is defined to be of the Account "type" - the argument sent to the constructor must be an instance of the Account class, in other words the constructor requires an Account object. So in order to construct a ConsoleAccountEvents object we must pass it an Account object as the argument as such:
Account acct = new Account();
ConsoleAccountEvents c1 = new ConsoleAccountEvents(acct)
Using "new" calls the constructor of the following class. For the Account class, we need no arguments to create an object - it has a default constructor, but we need to use an Account object - acct - as the argument to allow ConsoleAccountEvents to be constructed since it's constructor has an Account type parameter in it's definition.
In other languages there are more ways to construct objects. In C++ for example, the programmer can choose which objects should be saved on the "heap" and the "stack" by switching between using the new keyword vs calling the constructor directly as if it was any other function. In Java this is not possible. Almost all objects are created using the new keyword or by copying another object in some way. I believe even serializing and deserializing had to start with new at some point to create the first object.

Creating several objects of the same class

I need to create 10 objects from my Variable Class but I'm getting errors.
Here is my code:
for(n=1;n<10;n++){
variableTab[n]= "variable" +""+n;
Variable variableTab[n] = new Variable();
//System.out.println(variableTab[n]);
}
And the errors I have:
Type mismatch: cannot convert from Variable to Variable[]
Syntax error on token "n", delete this token
Duplicate local variable variableTab
I don't know where is the problem because variableTab[] is a String Tab.
You are trying to assign data to an object that hasn't been created yet. Also, you shouldn't start at index 1. Arrays begin at index 0, so essentially, you are robbing yourself of extra space and making things harder on yourself by doing that. This also means that you are creating 9 objects, not 10. Use the implementation below.
Variable [] variableTab = new Variable [10];
for(n=0;n<10;n++){
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Update per comments:
If you are trying to store the name of a object, you need to create a member variable to store that name in.
public class Variable {
private String name; //This will be used to store the unique name of the object
//Default constructor for our class
Variable () {
name = "";
}
//Constructor to initialize object with specific name
Variable (String name) {
this.name = name;
}
//We need a way to control when and how the name of an object is changed
public setName (String name) {
this.name = name;
}
//Since our "name" is only modifiable from inside the class,
//we need a way to access it from the program
public String getName () {
return name;
}
}
This would be the proper way to setup a class. You can then control the data for each class in a more predictable way, since it is only able to be changed by calling the setName method, and we control how the data is retrieved from other sections of the program by creating the getName method.
You might want to initialize your object first. If it is an array of objects that you're trying to create, do it this way:
Variable[] variableTab = new Variable[n];
You're trying to assign values to something that hasn't been created yet!
You're code should look like:
for(n=0;n<10;n++){
Variable variableTab[n] = new Variable();
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Basically, you're trying to assign a value to something that doesn't exist yet.

NullPointerException in while loop when trying to add new Class instances to ArrayList

The more I google this the more confused I'm getting.
I'm bringing in a list of names of unknown length with some other details in from a CSV which I then need to turn into Person objects and store in a list called people which is the instance variable for the class Club, a list of its members basically.
This is a very simplified version of something more complex I need to do in which I need to while loop through a file creating objects for each line which I then need to add to a list collection.
I keep getting a nullPointerException error when I run my code though and I'm stumped how to avoid it. I'm guessing that my variable p when I create the new object would need to change on each loop but I don't think it's possible to change variables dynamically is it?
Can't think how I can commit the object to the collection with a valid non null reference each time. Would be very grateful for any help. I've tried to cut out all the unnecessary stuff in the code below.
Thank you
//class arraylist instance variable of class "Club"
private ArrayList<Person> people;
//class constructor for Club
public Club()
{List<Person> people = new ArrayList<>();}
public void readInClubMembers()
{
//some variables concerning the file input
String currentLine;
String name;
String ageGroup;
while (bufferedScanner.hasNextLine())
{
//some lines bringing in the scanner input from the file
name = lineScanner.next();
ageGroup = "young";
Person p = new Person(); // i guess things are going wrong around here
people.add(p);
p.setName(name);
p.setAgeGroup(ageGroup);
}
}
Remove the List<Person> before people = … inside the constructor, otherwise you are declaring a new local variable people inside the constructor shadowing the field people (which is then never used). This leaves the class field uninitialized (null) and then causes the NPE.
What you want instead is initializing the field people:
public Club() {
// you can also use "this.people = …" to be explicit
people = new ArrayList<>();
}
To show the difference:
class Example {
private int myNumber;
public Example() {
myNumber = 42; // sets the field of the class
int myNumber = 1337; // declares a new local variable shadowing the class field
myNumber = -13; // accesses the object in the closest scope which is the local variable
this.myNumber = 0; // explicitly accesses the class field
}
}

instance variable in another class

I'm working on homework and I won't post the full code but I'm stuck on something that's probably simple and I can't find it in my book so I need to be pointed in the right direction.
I'm working with classes and interfaces.
Basically in my main code I have a line like this
CheckingAccount checking = new CheckingAccount(1.0); // $1 monthly fee
I was told to create a class called CheckingAccount and in that class I am told "This class should include an instance variable for the monthly fee that's initialized to the value that's passed to the constructor.
Since I'm new this is barely english to me and I'm assuming what that is saying is to take that 1.00 fee and declare it in the CheckingAccount class so I can create a method using that variable to calculate something.
soooo... How do I do that? I know how to create an instance variable it would be something like
public double monthly fee =
but then what? or I could be wrong. I am really doing bad at this java stuff. Any help is appreciated.
I guess another way to ask it is am I just declaring it as 1.0? or am I "importing" that value in case it changes later at some point you don't have to go through the code to change it in all of the classes?
Your requirement (as I read it) is to initialize the instance variable in the constructor, and your instantiation (new CheckingAccount(1.0);) shows you are on the right track.
What your class will need is a constructor method which receives and sets that value 1.0.
// Instance var declaration
private double monthly_fee;
// Constructor receives a double as its only param and sets the member variable
public CheckingAccount(double initial_monthly_fee) {
monthly_fee = inital_monthly_fee;
}
#Jeremy:
You're pretty much spot on (at least, your interpretation of what you've been asked to do matches my interpretation); while I don't know the actual design of the class, or whether monthly_fee needs to be public, in pseudocode you'd be looking at something like:
class CheckingAccount {
//Instance variable
double monthly_fee;
//Constructor
CheckingAccount(double monthly_fee) {
this.monthly_fee = monthly_fee;
}
//Function to multiply instance variable by some multiplier
//Arguments: Value to multiply the monthly fee by
double multiply_fee(double a_multiplier) {
return monthly_fee*a_multiplier;
}
}
You are basically right. If you haven't already, you should create a new class (it should be in it's own file called CheckingAccount) like this:
/** This is the class of Account with monthly fee. */
public class CheckingAccount {
// This is the instance variable.
// It should be 'private' for reasons you will surely learn soon.
// And NOT static, since that would be a class variable, not an instance one.
// The capitalization is called camelCase, google it up. Or, even better, find 'JavaBeans naming conventions'
private double monthlyFee;
// This is the constructor. It is called when you create the account.
// It takes one parameter, the fee, which initializes our instance variable.
// Keyword 'this' means 'this instance, this object'.
public CheckingAccount(double monthlyFee) {
this.monthlyFee = monthlyFee;
}
// Here will be your methods to calculate something...
}
Don't create an instance variable as public. It's bad practice because it violates the principle of information hiding (your teacher may call this abstraction). Instead, you can create an instance variable as
public final class CheckingAccount {
private double monthlyFee;
// The rest of the class goes here
public double getMonthlyFee() { // This method is called an accessor for monthlyFee
return monthlyFee;
}
}
Note that monthly fee isn't a valid variable name because it contains a space, and variable names can't contain spaces. Also notice that other classes access monthlyFee through a method. Because you define the method rather than making the variable public, you control access to monthlyFee a lot better (another class can't just change monthlyFee unless you define a method that makes that change).
Now to accessing monthlyFee. The method getMonthlyFee is called an accessor for a reason: it allows other classes to access that variable. So, those other classes can just call the method to get the monthly fee out of a CheckingAccount:
CheckingAccount checking = new CheckingAccount(1.0);
// A bunch of other code can go here
double fee = checking.getMonthlyFee(); // Now fee is 1.0

Categories