Click to See Complete Forum and Search --> : help with my simple method :( please
BuezaWebDev
10-16-2004, 09:28 PM
Okay, I've been doing php for a long time. I love it. I know about how to make functions that return things. However, I'm doing Java in school now...and I need help.
<?php
function bueza_foo($value) {
do stuff here
return $value;
}
$value = $_GET['value'];
$output = bueza_foo($value);
echo $output;
?>
How would I do the equivelent for Java??
1) Make function
2) Make it available to do certain things and then return a value??
Jeff Mott
10-16-2004, 09:35 PM
What have you tried so far?
You can't expect us to just hand you your homework. We will help you with it, but not do it for you.
BuezaWebDev
10-16-2004, 09:37 PM
lol, in the php code above, it practically explains what I want to convert to java.
is it with public static? private static?
I don't know how to start to create a method.
In PHP, I would just do function NameOfFunction (parameters), etc.
My thread isn't about handing me my homework. My question was simple. How do I make a method?
Edit: Jeff, you can consider your reply above this one as "spam" because you didn't even bother to state resources for me look at (websites that have tutorials). My thread isn't spam because I can't even do a search for my question. This board is completely new.
Sorry, but by you saying "we're not going to hand you your homework" to me; that just proves to me that you didn't read my thread correctly.
Edit again: Alright Jeff, it helps you out THAT much to answer my simple question.
import cs1.Keyboard;
public class MyFirstMethod
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Took like 10 seconds. I'm pissed off at people who try to answer my question with another question. Seriously.
buntine
10-16-2004, 10:23 PM
The basic syntax for a Java method is as follows
public ReturnType functionName(DataType varName)
{
// code
return value;
}
// Example
public int getSum(int x, int y)
{
return (x + y);
}
public - the method can be access from anywhere in your application.
private - can only be accessed from methods in the same class object.
protected - can be access from any object in the same package.
left blank - similar to public. You can look up the difference.
If you make your method static, it will be executed the moment the object is created. Only use static when it is necessary.
Regards.
BuezaWebDev
10-16-2004, 10:30 PM
Originally posted by buntine
The basic syntax for a Java method is as follows
public ReturnType functionName(DataType varName)
{
// code
return value;
}
// Example
public int getSum(int x, int y)
{
return (x + y);
}
public - the method can be access from anywhere in your application.
private - can only be accessed from methods in the same class object.
protected - can be access from any object in the same package.
left blank - similar to public. You can look up the difference.
If you make your method static, it will be executed the moment the object is created. Only use static when it is necessary.
Regards.
Perfect solution. Thank you Buntine.
To Jeff: Sorry for exploding on you--but believe it or not, I know how to ask a question and I knew that posting the code that had prior to Buntine's solution would be pointless because every java program starts with that.
I interpretted your response as a blatant attack against my intelligence. "We aren't going to hand you your homework"--Well, duh.
Again, I apologize.
EDIT
I have a question...with
public int getAverage(int a, int b, int c, int d, int e, int f)
{
int average = ((a+b+c+d+e) / f);
return average;
}
output = getAverage(1,2,3,4,5,5);
System.out.println(output);
//the output should be the average of 1+2+3+4+5 / 5 = 3
// The output will be 3.
Is that true? or am I totally doing this wrong?
buntine
10-17-2004, 12:27 AM
Looks fine to me. You could shorted your method to one line if you want.
It will provide no real performance gain, its just a matter of personal preferance.
public int getAverage(int a, int b, int c, int d, int e, int f)
{
return ((a+b+c+d+e) / f);
}
Regards.
ray326
10-17-2004, 12:27 AM
Originally posted by buntine
If you make your method static, it will be executed the moment the object is created. Only use static when it is necessary.
I don't think so. If you have an anonymous static block then *it* will be executed when the class is loaded but a static method (a class method) has to be called like any other function in order to be executed. We agree on the point that one should have a good reason for declaring anything static.
buntine
10-17-2004, 12:29 AM
Yer, thats right. The static method can to executed without declaring an instance of the object its within.
Regards.
BuezaWebDev
10-17-2004, 12:30 AM
Originally posted by buntine
Looks fine to me. You could shorted your method to one line if you want.
It will provide no real performance gain, its just a matter of personal preferance.
public int getAverage(int a, int b, int c, int d, int e, int f)
{
return ((a+b+c+d+e) / f);
}
Regards.
public int getAverage(int a, int b, int c, int d, int e, int f)
{
return ((a+b+c+d+e) / f);
}
How do I use the method??
just...
getAverage(); ??
buntine
10-17-2004, 12:33 AM
No, use it in the same way you demonstrated before. There is just no need to create a variable in the method if its not going to be used ot altered at a later point.
System.out.println(Integer.toString(
getAverage(1, 2, 3, 4, 5, 5)));
Regards.
ray326
10-17-2004, 12:37 AM
Jaime, I know you aren't coming up with those examples since you're taking a class but they are absolutely horrible if taken in the context of real world Java programming. They're just C. E.g. a method to get an average only makes sense as part of some kind of collection like a collection of temperature readings. A decent Java programmer would never create a stand alone average calculator.
ray326
10-17-2004, 12:41 AM
Originally posted by buntine
Yer, thats right. The static method can to executed without declaring an instance of the object its within. The latest version of our development tool has gotten even pickier than that. If you have a static method then it will complain if you call it relative to the object rather than the class. "not called in a static way" it whines. 8)
BuezaWebDev
10-17-2004, 01:02 AM
Okay. I've coded something up like this.
// Program will ask user to input a word
// Program will ask user to input a number of times to repeat the word
import cs1.Keyboard;
public class booya
{
public String RepeatWord(String iWord, int iRepeat)
{
if (iRepeat < 1) {
System.out.println("I cannot repeat the word less than 1 time. That's physically impossible.");
} else {
for (int count=1; iRepeat <= count; count++) {
do {
count++;
System.out.println (iWord);
} while (iRepeat <= count);
}
}
}
public static void main(String[] args)
{
System.out.println("Please enter the word that you wish to display: ");
String iWord = Keyboard.readString();
System.out.println("Please enter how many times you wish to repeat it: ");
int iRepeat = Keyboard.readInt();
System.out.println (RepeatWord(iWord, iRepeat));
}
}
However...it's spitting out one error.
System.out.println (RepeatWord(iWord, iRepeat));
Any suggestions?
BuezaWebDev
10-17-2004, 01:23 AM
Oops, how do you return more than one value???
HaganeNoKokoro
10-17-2004, 02:04 AM
There are a couple of ways to return more than one value.
If the values are all the same type, it can be done by putting them in an array. If they're not, you can still put them in an array of type Object (if you are going to put primatives like byte, short, int, long, float, double, char, boolean, and probably some more I am forgetting, you will have to wrap them in an Object to place them in the array [see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/package-summary.html for some of the pre-defined wrapper classes for primatives]), but this approach can get tricky, since once they're in there, to make any use of them, you will have to re-cast the references to whatever they were before, which may be a pain to figure out.
There is also a growable array-like structure in the java.util package called Vector, into which you can insert java.lang.Object. I can't off the top of my head remember if the Vector is a linked-list, or reallocating array, or what.
Other than that, you can make a custom object class with appropriate member variables to wrap the multiple return values in. Example: say you know you are always returning an int and a String. you would make a classclass MyWrapper {
int theInt;
String theString;
}To use, you could instantiate the class, set the values, and return the object.
buntine
10-17-2004, 02:25 AM
The ArrayList (Or List) object would be helpful. It is also in java.util.
Ues it as a dynamic array, that is, you can dynamically add and remove Objects to and from it.
Regards.
buntine
10-17-2004, 02:28 AM
Note, techically, a function can only return a single value. All we are doing here is grouping several values into one and sending that Object back to the calling environment.
Regards.
HaganeNoKokoro
10-17-2004, 02:46 AM
Well yeah, it wouldn't make much sense if a function actually returned multiple values. There would be ambiguity. It would rain muffins, we'd wear hats on our feet, and hamburgers would eat people. :eek:
BuezaWebDev
10-17-2004, 04:04 AM
I still don't understand why my function isn't being called. :|
I've been trying to debug it for a few hours already. lol. Gosh, I suck at Java.
Jeff Mott
10-17-2004, 04:30 AM
protected - can be access from any object in the same package.
left blank - similar to public. You can look up the difference.If it is left blank then it can be accessed by any class within the same package. If it is protected then it is accessible only within its own class and any class that extends it.
We agree on the point that one should have a good reason for declaring anything static.If you want a simple rule to follow: if a method does not use any instance variable then it should be static.
public int getAverage(int a, int b, int c, int d, int e, int f)
{
return ((a+b+c+d+e) / f);
}It doesn't make much sense to me to include the F parameter. The number (in this case) *must* be 5, otherwise the calculation will be wrong.
public int getAverage(int a, int b, int c, int d, int e)
{
return (a+b+c+d+e) / 5;
}
If you have a static method then it will complain if you call it relative to the object rather than the class. "not called in a static way" it whines.This is a good thing. It helps to keep what your program is doing more clear. I would think it would speed up execution time too (granting not very much).
public String RepeatWord(String iWord, int iRepeat)
{
if (iRepeat < 1) {
System.out.println("I cannot repeat the word less than 1 time. That's physically impossible.");
} else {
for (int count=1; iRepeat <= count; count++) {
do {
count++;
System.out.println (iWord);
} while (iRepeat <= count);
}
}
}First thing that sticks out is that you never actually return anything. The method should either return the repeated string and not print anything, or print the repeated string and return void.
Second thing, you are incrementing count in your loop body as well, which you shouldn't. In fact I think the entire do-while construct should be removed. As it is now it will leave you in an infinite loop.
BuezaWebDev
10-17-2004, 04:48 AM
ahhhhh...
How would I be able to make it print out a string depending on the input # that they put in??
If they put in 5 for input.
It'll print out....
foo
foo
foo
foo
foo
I'm so confused with the do-while loop.
buntine
10-17-2004, 06:17 AM
Thanks for that, Jeff.
It would be even more logical to simply use an array.
public int getAverage(int [] arr)
{
int total = 0;
for (int i = 0; i < arr.length; i++)
total += arr[i];
return (total / arr.length);
}
...
int [] avg = {1, 2, 3, 4, 5};
System.out.println(Integer.toString(
getAverage(avg)));
Regards.
BuezaWebDev
10-17-2004, 05:15 PM
Do I have to construct a new object just to use my own function/method ???
It keeps on saying a problem with System.out.println(repeatWord(iWord));
ray326
10-17-2004, 06:09 PM
If you want a simple rule to follow: if a method does not use any instance variable then it should be static. I like that one. Of course you then need to justify why that method was put into that class if the class itself is not some sort of utility class.
ray326
10-17-2004, 06:35 PM
Originally posted by BuezaWebDev
Do I have to construct a new object just to use my own function/method ???
It keeps on saying a problem with System.out.println(repeatWord(iWord)); I think your main problem is you're still not thinking in objects. (BTW, your RepeatWord() should be named repeatWord() because the convention is to capitalize classes and camel case almost everything else.)
Your method is being called but it's not returning a String as promised. To do that you'd have to do something like.
public String repeatWord(String iWord, int iRepeat)
{
StringBuffer sb = new StringBuffer();
if (iRepeat < 1) {
sb.append("I cannot repeat the word less than 1 time. "
+"That's physically impossible.");
} else {
for (int count=1; iRepeat <= count; count++) {
sb.append(iWord + " ");
}
}
return sb;
}
Your IDE is REALLY letting you down. Eclipse would never let you get away with not returning what you claimed you'd return.
BuezaWebDev
10-17-2004, 06:54 PM
Originally posted by ray326
I think your main problem is you're still not thinking in objects. (BTW, your RepeatWord() should be named repeatWord() because the convention is to capitalize classes and camel case almost everything else.)
Your method is being called but it's not returning a String as promised. To do that you'd have to do something like.
public String repeatWord(String iWord, int iRepeat)
{
StringBuffer sb = new StringBuffer();
if (iRepeat < 1) {
sb.append("I cannot repeat the word less than 1 time. "
+"That's physically impossible.");
} else {
for (int count=1; iRepeat <= count; count++) {
sb.append(iWord + " ");
}
}
return sb;
}
Your IDE is REALLY letting you down. Eclipse would never let you get away with not returning what you claimed you'd return.
I'm currently using JGRASP. :( NetBeans is weird--I can't even save the file to somewhere I want. :(
BuezaWebDev
10-17-2004, 07:11 PM
// Program will ask user to input a word
// Program will ask user to input a number of times to repeat the word
import cs1.Keyboard;
public class booya
{
public static String repeatWord(String iWord, int iRepeat)
{
StringBuffer sb = new StringBuffer();
if (iRepeat < 1) {
sb.append("I cannot repeat the word less than 1 time. "
+"That's physically impossible.");
} else {
for (int count=1; iRepeat <= count; count++) {
sb.append(iWord + " ");
}
}
return sb; // NetBeans keeps red underlining this line.
}
public static void main(String[] args)
{
System.out.println("Please enter a word: ");
String iWord = Keyboard.readString();
System.out.println("Please enter how many times you wish to repeat it: ");
int iRepeat = Keyboard.readInt();
System.out.println(repeatWord(iWord, iRepeat));
}
}
Hrmm...NetBeans keeps underlining the return statement. :|
HaganeNoKokoro
10-17-2004, 07:59 PM
It's probably because the return value for the method is a String but you are returning a StringBuffer. Also, I don't know if you can use System.out.println to print a StringBuffer. You may find you have to create a String from the StringBuffer in order to print it. Or if you want to return a string, return new String(sb);
BuezaWebDev
10-17-2004, 08:07 PM
REVISED.
Now it will just ask user to input the number of times to repeat the word "Alarm".
import cs1.Keyboard;
public class Alarm1
{
public int repeatWord(int x)
{
String output = "Alarm";
for (int count=1; x <= count; count++) {
System.out.println(output);
}
return output; // ERROR HERE?
}
public static void main (String[] args)
{
int input;
System.out.println("Yo, how many times do you want to repeat the word ALARM?");
input = Keyboard.readInt();
if (input < 1) {
System.out.println("Input is below 1. Error.");
} else {
System.out.println(repeatWord(input)); // ERROR HERE?
}
}
}
However, it keeps giving me an error on my last SYSTEM.OUT.PRINTLN and the RETURN line (incompatible types).
Please help. :(
HaganeNoKokoro
10-17-2004, 08:30 PM
public int repeatWord(int x)
{
String output = "Alarm";
for (int count=1; x <= count; count++) {
System.out.println(output);
}
return output; // ERROR HERE?
}Your return value is int, but you're returning a String. Of course it's going to complain. On another note, your loop looks pretty infinite to me, unless you call the function with x=0. If you just want a function to print the word those multiple times, make it with return value void, and return nothing:public static void repeatWord(int x) {
for(int i=0; i<x; i++) {
System.out.println("Alarm");
}
return; //note this return statement is optional
}Then in your main:public static void main (String[] args)
{
int input;
System.out.println("Yo, how many times do you want to repeat the word ALARM?");
input = Keyboard.readInt();
if (input < 1) {
System.out.println("Input is below 1. Error.");
} else {
repeatWord(input);
}
}
BuezaWebDev
10-17-2004, 08:39 PM
After much hassle. I've figured it out thanks to you guys!!!
/*
****************************************
****************************************
INPUT A NUMBER THAT WILL REPEAT
A WORD!!!
****************************************
* Author : Jaime Bueza
* Student Number: A00579330
* Date Created: October 17 / 2004
* Set: 1A
*****************************************
*/
// Let's have our program get the ability to take inputs from the user.
import cs1.Keyboard;
//Let's call our program, "alarm".
public class alarm
{
// Method Header: repeat Word
// Purpose of Method: To repeat the word "Alarm" as many times as the input.
// Parameters: iRepeat - the input value that is to be evaluated.
// Return: Returns the string "Alarm!" as many times as the input.
public static void repeatWord(int iRepeat) {
for (int x = 1; x <= iRepeat; x++) {
System.out.println("Alarm!");
}
}
// Alrighties, let's fire this baby up!!
// Ask the user to input a number to repeat the word "ALARM"
public static void main (String[] args) {
String inputNumber;
System.out.print("Enter a number: ");
inputNumber = Keyboard.readString(); // Input for it.
int numberConverted = Integer.parseInt(inputNumber);
// It's ERROR CHECKING TIME!!!!
// If the user inputs a number below 1, then spit out error.
// If the user inputs a number of 1 or above, then continue the process. :)
if (numberConverted < 1) {
System.out.println("Please enter a number again");
} else {
repeatWord(numberConverted);
}
}
}
That's the final. :D Thanks guys!! You're the best.
ray326
10-18-2004, 01:53 AM
Well crap. Just to finish up cleanly, yes you can't return sb you have to return sb.toString().