The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Private Variables

Private variables cannot be used over multiple classes. They are specific to the class in which they were created, hence the private part. You can declare a private variable by writing private before it, as seen below.

Many Methods & Instances

This post goes over how we can use multiple methods in different classes. It's a very inefficient program we've written, but it's designed to show you exactly what each method does and how they relate to each other. Here's Class2, the guts of the application. I've included comments to show you what everything does.

publicclass Class2 {//New stringprivateString friendName;/* This method is responsible for collecting the name
* variable we sent from the main method. We assign
* the variable friendName to the name collected in
* the main method. */publicvoid setName(String name){
friendName=name;}//New method with a return type of StringpublicString getName(){/* Basically just inserts the friendName variable
* into the getName method.*/return friendName;}//New method for finally outputting our name variablepublicvoid outputName(){//Outputs the variable getNameSystem.out.printf("Your friend's name is %s", getName());}}

The application basically outputs someone's name which we collect from Class1. Basically, we start by creating a friendName variable that we can use in Class2. It's going to be responsible for carrying our friend's name throughout the series of methods we've created here. Our first method, setName assigns the variable name (sent from Class1) to our friendName variable.

The next method, which is pretty useless, simply assigns the variable of friendName to the method of getName. This way we can use it in our last method, outputName by simply calling the getName method (which is storing our friendName variable). Let's take a look at Class1.

All we're doing here is creating a new object for Class2, followed by creating our name string, followed by sending this variable via our object through to the setName method in Class2.

I know it seems stupid using four different methods to output a simple variable, but it shows us how we can use multiple methods with multiple purposes for each to get the job done. Obviously this sort of setup would be better used had we had many more operations we wished to carry out.

Constructors

We can use a constructor to quickly initialise variables as soon as our object is created. If you haven't read the above post, please do - you will become familiar with the code we're using for these examples.

You can see what we've done here is added an argument of "Tony" to our class2Object. To use this constructor, you must make a method with the exact same name as the class in which it's in. Take a look at our Class2 code.

The method's name is Class2, identicle to that of our class name. Since we were able to send the name variable over to Class2 as the object was created, this now makes our setName method redundant. Its job has been taken care of.

Constructors are useful if we wanted to use multiple objects. Each object has its own set of variables. What we could do, if we wanted, would be to create another object like this.

Class2 class2Object2 =new Class2("Betty");

We could now decide to output class2Object2 or class2Object1; each would produce a different output.

Conditional Operators

Basically, I like to look at Conditional Operators as a quick way of implementing an If Statement. That's really all they are. Take a look at this code.

class Class1{publicstaticvoid main(String[] args){int age =50;System.out.println(age >30?"You are quite old!":"You are still young!");}}

You can see that we've initalised an integer with the value of 50. Our Conditional Operator then checks to see if it's greater than thirty (age > 30 ?). We use a question mark to see if the condition is true. You then write the true and false outputs separated by a colon. That's really all there is to it!

20 Tutorials Summarised!

Well, I've finally finished watching and summarising (in this thread) the first twenty tutorials of TheNewBoston's Java Programming Tutorial series. I've previously watched all 87 tutorials, but never summarised any of them to the point that the information stuck in my head long enough for me to retain.

I suppose you're right in saying that. The extent of my knowledge at the moment has the conditional operator acting like an If Statement in my head. Hopefully that will change when I start learning more things. Thanks for pointing that out mate.

Re: JD1's Personal Development Blog

Originally Posted by OA-OD-JD1

I suppose you're right in saying that. The extent of my knowledge at the moment has the conditional operator acting like an If Statement in my head. Hopefully that will change when I start learning more things. Thanks for pointing that out mate.

Well thinking about it as an if/else statement is probably pretty okay, as long as you know that they have to return values (of the same type) and not execute a block like an if statement does.

Firstly, we must import the scanner, since it's not available in the default library. It's found in the java.util library, so we write import java.util.Scanner; at the top of our code to allow us to use the scanner. Capitalisation here is important.

Next, we need to create a new scanner variable to let us use the scanner. Do this by typing Scanner followed by the name of the object (in this case, I called mine input). Set the object equal to new Scanner with the parameter of System.in - this allows us to read the keyboard input.

Now whenever you type into the console (or other field), the text you enter before pressing enter will be stored in the input scanner variable. To output this, we need to figure out what data type we're working with. In this case, it's a string of text so we use input.nextLine(). That's really all there is to it!

Re: JD1's Personal Development Blog

Well thinking about it as an if/else statement is probably pretty okay, as long as you know that they have to return values (of the same type) and not execute a block like an if statement does.

So, basically, I'm limited to the amount of things I can do in the Conditional Statement? Whereas in an If Statement, you can really have as many instructions as you want. I suppose I can only output a variable using a Conditional Statement, and not a series of instructions, right?

How could I change this to make it more challenging to create? I could have used multiple classes or multiple methods to do various tasks. For example, one method could be used to loop through the inputs, and another could be used to find the average. In fact, I'm going to do this now. Check it out.

I managed to use the main method for the introduction and to call the second method. I tried using three methods, one for the main method, one for the loop, and one for the average, however, when I tried sending variables from the loop method to the average method, it was reading the variables from the main method. I wasn't sure how to go about fixing this, so if anyone could help out, I'd really appreciate that. I'll look into it myself now.

But then how would this know to get the total from the loop method and not the main method? And I want to send the total from the loop method and the numGrades from the main method? Not sure how to go about doing this.

Re: JD1's Personal Development Blog

Originally Posted by Mr.777

There are also third type of comments and they are Java Doc Comments.

I forgot to mention that. I actually haven't yet learned about the functionality of these comments, so I'll make sure to edit that post when I know what I'm talking about. Thanks for pointing that out mate.

Re: JD1's Personal Development Blog

But then how would this know to get the total from the loop method and not the main method? And I want to send the total from the loop method and the numGrades from the main method? Not sure how to go about doing this.

Make the total as Instance variable and use getTotal() as getters method of your class so that you could use it anywhere and mark total as private(if it's instance variable).

Re: JD1's Personal Development Blog

Okay, with relevance to my last post about the averaging calculator, I've written up the application exactly as I'd like it to look. The only problem is the variables, that's the last step. I've taken a screenshot to show you where the errors are.

Here's the code.

/* The application will work as follows. The main method will be used to reference the
* other methods into action. It will also produce an introductory message telling the
* user to input a certain number of grades. There will be a loop method responsible for
* looping through the grades and finding a total. The average method will take this total
* and use the number of grades (mentioned in the main method) to find the average. It will
* then output the average of the greades.*/importjava.util.Scanner;class Class1{//This method is responsible for the intro' message and for introducing all other methods.publicstaticvoid main(String args[]){int numGrades;System.out.print("Please enter the number of grades you wish to work with: ");
Scanner numGradesInput =new Scanner(System.in);
numGrades = numGradesInput.nextInt();System.out.println("You've chosen to average "+ numGrades +" grades. Please enter these grades now.");}//This method is responsible for finding the total of the grades.publicvoid loop(){int grade;int total;int counter =0;
Scanner gradeInput =new Scanner(System.in);//This loop finds the total.while(counter < numGrades){
grade = gradeInput.nextInt();
total = total + grade;
counter++;}//The total now needs to be sent to the averaging method.}//This method is responsible for finding the average of the total found in the loop method.publicvoid average(){int average;
average = total/numGrades;System.out.println("The average of the "+ numGrades +" grades you entered is "+ average +".");}}

Re: JD1's Personal Development Blog

Yeah they are marked with red underline because they are not initialized. And also they are local variables not instance variables. Only instance variables get auto initialized. You must initialize numGrades and all other local variables before using them.

Re: JD1's Personal Development Blog

Originally Posted by Mr.777

Yeah they are marked with red underline because they are not initialized. And also they are local variables not instance variables. Only instance variables get auto initialized. You must initialize numGrades and all other local variables before using them.

That's what I'm trying to do. This is what I ended up with. No errors, but it won't let me input anything into the console.

/* The application will work as follows. The main method will be used to reference the
* other methods into action. It will also produce an introductory message telling the
* user to input a certain number of grades. There will be a loop method responsible for
* looping through the grades and finding a total. The average method will take this total
* and use the number of grades (mentioned in the main method) to find the average. It will
* then output the average of the greades.*/importjava.util.Scanner;class Class1{//This method is responsible for the intro' message and for introducing all other methods.publicstaticvoid main(String args[]){int numGrades;System.out.print("Please enter the number of grades you wish to work with: ");
Scanner numGradesInput =new Scanner(System.in);
numGrades = numGradesInput.nextInt();System.out.println("You've chosen to average "+ numGrades +" grades. Please enter these grades now.");
Class1 class1Object =new Class1();
class1Object.setNumGrades(numGrades);}//Testingprivateint numGradesFromMainMeth;publicvoid setNumGrades(int mainMethNumGrades){
numGradesFromMainMeth = mainMethNumGrades;}publicint getNumGrades(){return numGradesFromMainMeth;}//\Testing//This method is responsible for finding the total of the grades.publicvoid loop(){int grade;int total =0;int counter =0;
Scanner gradeInput =new Scanner(System.in);//This loop finds the total.while(counter < numGradesFromMainMeth){
grade = gradeInput.nextInt();
total = total + grade;
counter++;}//The total now needs to be sent to the averaging method.}//Testingprivateint numTotalFromLoopMeth;publicvoid setTotalFromLoopMeth(int totalFromLoopMeth){
numTotalFromLoopMeth = totalFromLoopMeth;}publicint getTotal(){return numTotalFromLoopMeth;}//\Testing//This method is responsible for finding the average of the total found in the loop method.publicvoid average(){int average;
average = numTotalFromLoopMeth/numGradesFromMainMeth;System.out.println("The average of the "+ numGradesFromMainMeth +" grades you entered is "+ average +".");}}

You probably can't understand that because I've named variables horrendously.

After spending another hour trying to figure out how this is done, I'm going to give up for the time being. I think I need to do a little more work with methods before trying this again. Thanks for your help, Mr.777.

Compound Interest Calculator

Compound interest can be calculated with the following formula.

A = Amount
P = Principal
R = Rate
n = Years

A=P(1+R)^n

We can calculate the amount in Java as shown below. We currently know the principal (10,000) and the rate (1%). The years can change depending on how much information we want. In this application, we'll just use 20.

We initialise our variables as per usual. We then construct a For Loop which will give us 20 iterations. Using our formula, we calculate the amount. We used the Math.pow function because it allows us to use indices. The first parameter is what you want in the parentheses and the second parameter is what you want the power to be. Quite a simple calculator.

I managed to send the grades from the main method using class1Object. The only thing preventing me sending the total from the loop method to an average method is that I can't use the class1Object outside of the main method. How can I do this?

Do While Loop

We use the Do While Loop when we want to run a set of instructions before testing to see if a condition is true. The difference between a Do While Loop and a While Loop is that the While Loop tests the condition first and then runs the instructions.