help with creating a method and returning a value
Hi. I am having trouble understanding some simple concepts. I am frustrated.
I typed this simple code and it counts up by three's.
import acm.program.*;
public class Freespace extends ConsoleProgram {
private static final int MAX_COUNT = 300;
public void run() {
println("Count upwards by 3's");
for (int i = 0; i <= MAX_COUNT; i = i + 3) {
println(i);
}
}
}
I want to create a private method that does the counting for me and then returns it to the public method, but I am stuck.
I basically want the method to be called countThree and have the calculations and for loop done there. Please help. My textbook is vague on its example and Google results are always in a different library I dont know the syntax of yet.
Re: help with creating a method and returning a value
The code you posted is a method with code inside it. What do you want to change about the method you have posted? What do you want the new method you are working on to do?
See the tutorial about methods: Defining Methods (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
One problem I see is that you are using 3rd part classes and are NOT using java SE classes and methods. That can make many of the responses you get here not make sense.
Why are you using the acm packages instead of the java SE packages and clases?
Re: help with creating a method and returning a value
The ACM packages are part of The Art and Science of Java textbook... the source of my learning.
Basically, I am learning information hiding and would like the main public class to receive the code that counts by three from the new Private method I create.
It is hard for me to elaborate.
--- Update ---
import acm.program.*;
public class Freespace extends ConsoleProgram {
private static final int MAX_COUNT = 300;
public void run() {
println("Count upwards by 3's");
// now I want to get a return result from the new method countThree below
private int countThree() {
for (int i = 0; i <= MAX_COUNT; i = i + 3) {
println(i);
}
//how can I get this result returned to the public void
}
}
Re: help with creating a method and returning a value
Quote:
get this result returned
Use the return statement.
See the tutorial: http://docs.oracle.com/javase/tutori...turnvalue.html
When posting code Please wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
Re: help with creating a method and returning a value
The countThree() method doesn't have anything to return that I can see. It is designed to count (print) and that's all.