• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Java - how to call a header file

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Xtreme Barton

Member
Joined
Jan 17, 2004
ok ill be able to provide more info when i get home but i was hoping to get some hits in between that time maybe someone will point right direction..



i created a header file for my name, instructor, and class...



now i have another program im creating where id like to call that header file.

i think i need to add the file into the appropriate project im working with. but im stuck on how to code it into my main() .. and also if i need to include anything else before my main()..


hopefully its pretty clear if not ill post up more in depth instructions as provided.

ive been stuck on this for a few hours :(
 
Call your new personal heading class’s getHeading(…) method from InterestCalculatorApp’s main(…) and pass the String “Assignment Two” in the argument. For example, mine would be coded, YourLastNameHeading.getHeading(“Assignment Two”)
 
Usually the heading for a file is just a comment not a method that you call.

For example I took this out of the GIMP source code

Code:
/* GIMP - The GNU Image Manipulation Program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *//

See how at the top it contains the name of the program, the authors with their copyright and a copy of the license.

For you it may contain the name of your teacher/class and some information about the assignment.
 
Still stumped .. as i see wut yur saying but assigment wants me to call a seperate header i created .. i put class files in appropriate location of project i just cant figure out what he request in my second post
 
You put your "heading" class into a package, and then use the import statement to import that class from the package into your project. See http://docs.oracle.com/javase/tutorial/java/package/index.html for how that all works. Basically, if inside your project's source folder you had /utils/MyHeadingClass.java, you'd use import utils.MyHeadingClass. After that you could call MyHeadingClass.getHeading().

Ideally, if this class is something you'll use in multiple projects, you wouldn't keep it in any one project's source directory. Instead you'd keep it in a common library location and make all of your projects check this location when doing an import. You'll need to ask an actual Java person what the best way to do that is, though. The important thing is that you aren't just copy+pasting your code into each new project that needs it. If you're copy+pasting existing code, then you probably need to rethink what you're doing.

For the record, the term "header file" means something different to most coders than what you're trying to do here, which may have caused some people to ignore this thread as being a silly question. What you're asking about is how to package and import a class in Java. Once you become more familiar with the terminology it'll be much easier to ensure that people understand what you're asking, and it makes searching for that info much easier as well.
 
No...packages and import have nothing to do with what you are asking for. Import statements bring in classes and groups (packages) of classes. You are just looking for a standard file header at the top of each file...whether that file represents a class, interface, enum, or whatever. There is nothing in the language that does this. The good news is that most IDEs do support this function...in multiple ways:


IntelliJ:


The template approach allows you to use rich velocity scripting or just specify an "include". I haven't tried that plugin.


Eclipse has similar functions:

  • Main Menu -> Window -> Preferences -> Java -> Code Style -> Code Templates -> Configure generated code and comments, or
  • Comments -> Files -> Edit


regards,
Scuba
 
Your correct in what im trying to achieve and yes my terminology is limited. Im completely fresh to java and pretty much all programming.


Anyway that is wut im trying to achieve. To be able to use that for every new project i create ..

Sorry for confusion



You put your "heading" class into a package, and then use the import statement to import that class from the package into your project. See http://docs.oracle.com/javase/tutorial/java/package/index.html for how that all works. Basically, if inside your project's source folder you had /utils/MyHeadingClass.java, you'd use import utils.MyHeadingClass. After that you could call MyHeadingClass.getHeading().

Ideally, if this class is something you'll use in multiple projects, you wouldn't keep it in any one project's source directory. Instead you'd keep it in a common library location and make all of your projects check this location when doing an import. You'll need to ask an actual Java person what the best way to do that is, though. The important thing is that you aren't just copy+pasting your code into each new project that needs it. If you're copy+pasting existing code, then you probably need to rethink what you're doing.

For the record, the term "header file" means something different to most coders than what you're trying to do here, which may have caused some people to ignore this thread as being a silly question. What you're asking about is how to package and import a class in Java. Once you become more familiar with the terminology it'll be much easier to ensure that people understand what you're asking, and it makes searching for that info much easier as well.
 
ok im still having troubles with this :(

i created my own personal heading class in a previous tutorial. Now im suppose to call my personal heading class's getHeading() method from main and pass a string arguement.

here is what im working with

HTML:
/** Murach's Java SE 6; Murach, Steelman; Murach Publishing, (c) 2007
 InterestCalculatorAppStarter.java  
        Modified by Wm Bowers 2008 - 2011
 STARTER CLASS
        Modified by D.Keller, March 2012
*/
package interestcalculatorapp;
 
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.*; // for Date class
import java.text.*; // for Date & DateFormat class
 

public class InterestCalculatorApp
{
 
    public static void main(String[] args) 
    
{
       
        
       
        
        
        
        
        
        // display a welcome message
        System.out.println("Welcome to the Interest Calculator\n");
        // create the Scanner object
        Scanner sc = new Scanner(System.in);
        // perform conversions until choice isn't equal to "y" or "Y"
        String choice = "y";
        while (choice.equalsIgnoreCase("y")) {
            // get the loan information from the user
            System.out.print("Enter loan amount:   ");
            double loanAmount = sc.nextDouble();
            System.out.print("Enter interest rate: ");
            double interestRate = sc.nextDouble();
            System.out.println();
            // calculate the interest amount
            double interest = loanAmount * interestRate;
            // format setups
            NumberFormat percent = NumberFormat.getPercentInstance();
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            // display the results
            System.out.println("Loan amount:         " + currency.format(loanAmount));
            System.out.println("Interest rate:       " + percent.format(interestRate));
            System.out.println("Interest:            " + currency.format(interest));
            System.out.println();
            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
        }
    }
 
ok man i feel silly for overlooking this .. hopefully this is the correct solution to what is asked.

:bang head :bang head

i used import

HTML:
 import kellerheading.KellerHeading;

and down in main i used

HTML:
KellerHeading.getHeading("Assigment Two");
 
Sorry I'm not totally sure it is what you are trying to accomplish with your getHeading method. Maybe if you posted the exact text of the assignment it would help. We won't do it for you but we can guide you in the right direction.

Either way some small nitpicky stuff

Take for example these 4 lines

Code:
        // display a welcome message
        System.out.println("Welcome to the Interest Calculator\n");
        // create the Scanner object
        Scanner sc = new Scanner(System.in);

Take those comments out they are totally unnecessary. I would advise you to look at this coding style sheet from Stanford's CS106A intro to programming class. Basically comments should be meaningful and help you understand the code (lets say you are looking back at an old project) or other people who are reading it.

Take for example

Code:
// Sets double value to 3.0
double foo = 3.0;

The comment is unnecessary because it is obvious the code sets foo to 3.0 (BTW don't use foo as a variable name. it is a crappy name. Variable names should be meaningful too). Same with // create the Scanner object. That is obvious when you call Scanner sc = new Scanner(System.ln); the comment doesn't add anything meaningful. You have quite a few of these like for example when you calculate the interest amount. It makes the code harder to read.

Here are some more Stanford Handouts which may help you.
 
Last edited:
i here ya with the comments .. those were proivded in the package and i wasnt sure if i should have altered anything other than what my instructions said. although it does say im allowed to modify it ... ehh so i left it in
 
Call your new personal heading class’s getHeading(…) method from InterestCalculatorApp’s main(…) and pass the String “Assignment Two” in the argument. For example, mine would be coded, YourLastNameHeading.getHeading(“Assignment Two”)

Ok, it is pretty confusing what you are trying to do but I think I understand.

Ok here is how I understand it:

1) You have a class called Heading.java (or similar. Would it be Heading.class? I haven't done java in a while)
2) Inside that class you have a public method called getHeading() which may look as follows

Code:
/* Returns a heading based on inputted string*/
public String getHeading(String assignment) {
	//Psuedocode:
	//String manipulation
	//Return completed string
}

3) Then in your other program your interest one you want to call that method so that when main is run it prints out all the heading information (i.e. your name, assignment number, teacher, ect.)

If that IS in fact what you want to do what you have to do is inside your interestcalculatorapp

1) Create a heading object for example if your Heading class is called Heading.java

Code:
Heading headingObject = new Heading();

2) Then have this object call that method:

Code:
String heading = headingObject.getHeading("Assignment Two");
System.out.println(heading);
 
Last edited:
I second the "hard to understand what you are trying to do" statements. :D

A "header file" has a pretty specific meaning (not applicable to Java) in programming which is probably what is confusing everyone here.

http://en.wikipedia.org/wiki/Header_file

Let me help try to clear up some confusion with the terms since you say you are just starting.

A class defines an object. The way my teacher explained it a pretty good way. Let's say you have a class called Human. The class would define everything a human would have say for example a name (maybe a String) a biological sex (maybe a boolean). Then each actual person would be an object of that class

For example:

Code:
Human TimTebow = new Human("Tim Tebow", true);

This would create a new human object. Then that particular object can go do things that humans do like TimTebow.throwFootball().

Another thing you will want to learn is decomposition (you may not be that far in your class yet). That is breaking down your project into smaller parts/problems. For example my teacher explained it this way. If someone asked you how you get ready in the morning you may say:

  • Get Up
  • Get Dressed
  • Brush Teeth
  • Leave

But it really isn't that simple if you think about it. For example Get Dressed may involve:
  • Put on pants
  • Put on Shirt
  • Put on Socks

and Brush Teeth may involve:
  • Grab Toothbrush
  • Put toothpaste on Brush
  • Rub against teeth for 2 minutes
  • Spit
  • Rinse

So right now your program you listed has everything in main. Later on that will become an issue and you can't do that. You want to use methods firstly because it makes your code cleaner and because you can REUSE them. For example take this method:

Code:
/* Returns the Fahrenheit equivalent of the Celsius temperature c. */
	private double celsiusToFahrenheit(double c) {
		return 9.0 / 5.0 *c + 32;
	}

This means any time later in your program when you want to convert c to f you don't have to rewrite code because bam! you have already done it and you only have to do it once. The other advantage to using methods is you only have to change the method in one place. Lets say you are calculating something more complicated then interest and you have to do it 10 times in a program. You could do it two ways. You could write a method one time to do it and then call it every time or you can write out the equation to calculate it 10 times every time it is needed in the program. But then lets say in the future some more efficient/simpler equation is developed to calculate the same thing but it is faster or requires less steps. If you had written a method to do it you can simply go change the code in that one place and bam you are done. If you wrote the equation out 10 times you would have to change the code in 10 different places. You don't want to have to do that.

You don't really want to be re-writing code. For example your line:

Code:
double interest = loanAmount * interestRate;

I would turn that into a method because in a large program you may need to calculate interest multiple times.
 
Last edited:
man im really hating online course already.

you guys are confused to as to what is wanted for the program. except the problem lies in the instructions. what i posted is exactly what i got for my instructions.

from post #2 on is what i have available to me.

text book
assigment

what i do is open up a provied project and alter it according to the assignment instructions.

previous instructions to the ones posted in POST# 2 required me to modify a personal heading class and date class.

then to -
Call your new personal heading class’s getHeading(…) method from InterestCalculatorApp’s main(…) and pass the String “Assignment Two” in the argument. For example, mine would be coded, YourLastNameHeading.getHeading(“Assignment Two”)

sorry guys my best def isnt cutting it in these early stages .. class room would be 10000% better for me.
 
Ok, so here are a few reasons why we are confused:

1) What you put in post #2 is that the exact word for word text of the problem? Or are you putting it in your own words. If you are putting it in your own words don't. Copy and paste it here so we can read it.

2) At this point in time I am fairly sure there is a big chunk of code we are not seeing. You keep saying you have a "personal heading class" can you post the code for that class. It obviously has some method in it called getHeading(String heading) (or maybe it is your assignment to write this method). Post both the code for the interest calculator program AND the header class

3) You keep talking about this:

Code:
YourLastNameHeading.getHeading(“Assignment Two”)

This is confusing as hell because what you have is an object (YourLastNameHeading) which came out of nowhere calling a method (getHeading(String)) but you haven't shown us any of the details about these. Objects have to be created before they can be used. YourLastNameHeading seemingly comes out of nowhere (or not in any code you have posted). Secondly, where does this getHeading(String) method come from? As far as I can guess it comes from some other file you have not showed us which is why we are really struggling to help you.

If these terms confuse you ask us and we will try to explain them:
  • Class
  • Object
  • Method (may be called a function)

TL;DR: We are not understanding because you are not showing us the whole problem. You are not showing us all the code (probably this header class you refer to)
 
Last edited:
3) You keep talking about this:

Code:
YourLastNameHeading.getHeading(“Assignment Two”)

This is confusing as hell because what you have is an object (YourLastNameHeading) which came out of nowhere calling a method (getHeading(String)) but you haven't shown us any of the details about these. Objects have to be created before they can be used. YourLastNameHeading seemingly comes out of nowhere (or not in any code you have posted). Secondly, where does this getHeading(String) method come from? As far as I can guess it comes from some other file you have not showed us which is why we are really struggling to help you.

If these terms confuse you ask us and we will try to explain them:
  • Class
  • Object
  • Method (may be called a function)

TL;DR: We are not understanding because you are not showing us the whole problem. You are not showing us all the code (probably this header class you refer to)

If it's a static class / method it won't have to be initiated before use.
 
ok ill be able to provide more info when i get home but i was hoping to get some hits in between that time maybe someone will point right direction..



i created a header file for my name, instructor, and class...



now i have another program im creating where id like to call that header file.

i think i need to add the file into the appropriate project im working with. but im stuck on how to code it into my main() .. and also if i need to include anything else before my main()..

Once a class is included in the project it will work like any other class, it does not matter if you are reusing it between different projects.

So, if it's a static method you can just call it like you are doing now, if not you first have to create an instance of the class before calling it's methods.

Also, it does not matter if you are calling it from your main or other methods, from a dependency point of view there should be no difference.

If they are in the same package you should not need to have any import statements before your main method (I'm assuming that's what you mean), however if you are already using package names for your projects, you should check that they match (that is, change it to match whatever you are working on).

Later on you can package reusable "utility" classes into a jar package which you will import, and be able to reuse (I'm assuming you have not gotten that far yet so don't bother thinking about this too much yet).
 
Back