Posted by: techGuy November 12, 2008
Java help Needed!
Login in to Rate this Post:     0       ?        

oops i didnt see ur second post.

So you want to pass string as a paramter right.

That means your class will now should accept parameter.

Two ways you can do this.

Either use constructer, so that whenever you create an object out of your MyStringTest class, the string member is initialized.

Remember the constructer name is always same as the class Name, so in your case the constructer name will be MyStringTest

Now this is how your code will look like

class MyStringTest

{

String name;

public MyStringTest(String temp)//constructer that initializes your object

{

name=temp;

}

public void reverse()

{

int len = name.length();

String s="";

for(int i=len-1; i>=0; i--)

{

//Get the character at that index

char c=name.charAt(i);

//convert that char to string

String s1 = Character.toString(c);

//concatenage each returned string till the loop is completed

s=s.concat(s1);

}

System.out.println (s);

}

 

 

}

public class test

{

public static void main(String args[])

{

MyStringTest mst = new MyStringTest("sajha"); //creates an instance of the class you created above

mst.reverse(); //calls the method inside you class

}

}

 

The second method is by making your method "reverse" to take a String as an argument.

So you dont need a constructer right. And you wont even need String member variable, since you will be passing that from main method. Then your code will be something like this

class MyStringTest

{

public void reverse(String name)

{

int len = name.length();

String s="";

for(int i=len-1; i>=0; i--)

{

//Get the character at that index

char c=name.charAt(i);

//convert that char to string

String s1 = Character.toString(c);

//concatenage each returned string till the loop is completed

s=s.concat(s1);

}

System.out.println (s);

}

 

 

}

public class test

{

public static void main(String args[])

{

MyStringTest mst = new MyStringTest(); //creates an instance of the class you created above

mst.reverse("sajha"); //calls the method inside you class

}

}

 

Last edited: 12-Nov-08 09:22 PM
Read Full Discussion Thread for this article