Results 1 to 6 of 6
Thread: my java programe
- 12-09-2010, 11:21 AM #1
Member
- Join Date
- Nov 2010
- Posts
- 18
- Rep Power
- 0
my java programe
i created a programe and passed a value but didnt work why?
public class mymethod {
int myint;
void method1(int value){
value=myint;
method2(" sri lanka" );
System.out.println(value);
}
void method2(String myst){
}
}
public class mymain {
public static void main (String[]args){
mymethod obj=new mymethod();
obj.method1(5100);
}
}
- 12-09-2010, 11:38 AM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
Well, seeing as how that program does not do anything ...
However, describe "does not work", that is the singularly most useless problem description in the world.
However, why do you set the local passed value to the undeclared instance variable value (instead of the other way around), and then do nothing with it, and then call another method with a hard-coded string (and that method is empty). What was the argument for, either time?Last edited by masijade; 12-09-2010 at 11:58 AM.
- 12-09-2010, 11:42 AM #3
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
Please use CODE tags.
Might as well learn good style when you're just starting out, rather than develop bad habits. Class names should start with a capital letter, and if they're two words, capitalize the subsequent ones.Java Code:public class [COLOR="Blue"]MyMethod[/COLOR] {
This is an instance variable, and when you don't specify otherwise, it's package-protected. Get in the habit of making your instance variables private, until you have a good reason to do otherwise. It's better for encapsulation. Other classes should interact with your class via its public API, not by messing around directly with its state.Java Code:int myint;
Your method was passed the parameter value, but you've overwritten it with whatever was in your instance variable myint -- which is nothing at all. I think maybe you intended to do that the other way around.Java Code:void method1(int value) { value = myint;
Did you mean to do something there?Java Code:method2(" sri lanka" ); System.out.println(value); } void method2(String myst){ }
}
This is legal, but you really don't need a separate class here. This would work just as well:Java Code:public class [COLOR="Blue"]MyMain[/COLOR] { public static void main (String[] args) { [COLOR="Blue"]MyMethod[/COLOR] obj = new [COLOR="Blue"]MyMethod[/COLOR](); obj.method1(5100); } }
-Gary-Java Code:public static void main(String[] args) { // still in MyMethod class MyMethod obj = new MyMethod(); obj.method1(5100); // or even just this: (new MyMethod()).method(5100); } }
- 12-09-2010, 02:58 PM #4
Member
- Join Date
- Dec 2010
- Posts
- 45
- Rep Power
- 0
- 12-09-2010, 03:01 PM #5
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
:headdesk:
- 12-10-2010, 07:35 AM #6
Member
- Join Date
- Dec 2010
- Posts
- 3
- Rep Power
- 0


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks