Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

If then statement and loop

Status
Not open for further replies.

redletterrocko

Programmer
Aug 8, 2005
53
US
Alright, I'm COMPLETELY new to Java. I went and bought one of those "Learn Java in 60 seconds!" kind of books, and am trying to develop a quick piece of software in it, just to see if it's something I should continue with. I know very little, so you'll have to talk VERY SLOWLY...

So I have created multiple instances of an object (we'll call them Handgun1, Handgun2, Handgun3, etc) Each has a boolean attribute we'll call "Loaded" I would like to create a very simple procedure that would check all instances and see if Loaded=1, and if it does, to print something like "Handgun1 is loaded" to the console. The program itself is pretty simple other than that. Could someone at least point me in the right direction. I'm pretty lost... I'm assuming it would have to loop for each instance, but maybe you can come up with something better.
 
You can create an object array. Something likes:

HandGun handgun[4] = new HandGun


handgun[1].load(); //this will change Loaded flag to 1
handgun[2].load();

Then you can use a loop to check the object state

for(int i = 0; i<handgun.length;i++){
if(handgun.Loaded = 1)
System.out.println("sssssss");
}



 
@wangdong
It's a very good idea to use an array instead of hg1, hg2, because we don't need to write nearly identical code multiple times, and may increase the number of handguns easily.

But:
You need an Array on the right side and a semicolon.
You need to initialize the elements of the array.
You don't need to check a boolean with (hg.loaded == true), but may directly check 'if (hg.loaded) - you need '==' for comparision while '=' is used for assignment, and you may not use an int like '1' instead of 'true'.

Code:
HandGun handgun[] = new HandGun [4];

for (int i = 0; i < handgun.length; i++)
{
	handgun[i] = new HandGun ();
}

handgun[1].load ();
handgun[2].load ();

for (HandGun hg : handgun)
{
	if (hg.loaded)
		System.out.println ("loaded");
}
You may use the enhanced for-loop like shown here if you use java 5.
Accessing the boolean attribut directly is discouraged - a better way would be to make it privat, and access it by a method: if (hg.isLoaded ()).

@redletterrocko
An ArrayList instead of an array would be more flexible. You could modify the number of handguns in the collection.
Attributes are written with initial lowercase letter (loaded, not Loaded) by convention.
Understanding code is much more easy, if people stick to these conventions.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top