Get String From Another Method? - java

I have two methods, the first one creates a string, then I want to use that string in the second method.
When I researched this, I came across the option of creating the string outside of the methods, however, this will not work in my case as the first method changes the string in a couple of ways and I need the final product in the second method.
Code:
import java.util.Random;
import java.util.Scanner;
public class yaya {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Random ran = new Random();
int ranNum = ran.nextInt(10);
input = input + ranNum;
}
public void change(String[] args) {
//more string things here
}
}

Create an instance variable:
public class MyClass {
private String str;
public void method1() {
// change str by assigning a new value to it
}
public void method2() {
// the changed value of str is available here
}
}

You need to return the modified string from the first method and pass it into the second. Suppose the first method replaces all instances or 'r' with 't' in the string (for example):
public class Program
{
public static String FirstMethod(String input)
{
String newString = input.replace('r', 't');
return newString;
}
public static String SecondMethod(String input)
{
// Do something
}
public static void main(String args[])
{
String test = "Replace some characters!";
test = FirstMethod(test);
test = SecondMethod(test);
}
}
Here, we pass the string into the first method, which gives us back (returns) the modified string. We update the value of the initial string with this new value and then pass that into the second method.
If the string is strongly tied to the object in question and needs to be passed around and updated a lot within the context of a given object, it makes more sense to make it an instance variable as Bohemian describes.

Pass the modified string in the second method as an argument.

create a static variable used the same variable in both the method.

public class MyClass {
public string method1(String inputStr) {
inputStr += " AND I am sooo cool";
return inputStr;
}
public void method2(String inputStr) {
System.out.println(inputStr);
}
public static void main(String[] args){
String firstStr = "I love return";
String manipulatedStr = method1(firstStr);
method2(manipulatedStr);
}
}

Since you mentioned that both methods should be able to be called independently, you should try something like this:
public class Strings {
public static String firstMethod() {
String myString = ""; //Manipulate the string however you want
return myString;
}
public static String secondMethod() {
String myStringWhichImGettingFromMyFirstMethod = firstMethod();
//Run whatever operations you want here and afterwards...
return myStringWhichImGettingFromMyFirstMethod;
}
}
Because both of these methods are static, you can call them in main() by their names without creating an object. Btw, can you be more specific about what you're trying to do?

Related

How can I use a user input String from one method in another?

This point of this program is to limit the character length of a username to 20 characters. It is one part of a larger program which currently only contains a Main method. In the interest of cleaning and clarifying my code, I would like to separate the various functions into distinct methods.
Currently, I'm trying to set class variables so that they can be used in multiple methods. This is what I have so far:
public class Program
{
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void main(String[] args) {
domainCharLimit();
}
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
I have tried setting one or both methods to static, which did not resolve the issue. In this state, when run, the program will not return an errors but rather give "no output"
Main method has to be static! It is entry to your program and its signature has to be like that.
In order to call non static method inside it you need to instantiate an object and call it on that object. In your case something like
public static void main(String[] args) {
Program p = new Program();
p.domainCharLimit();
}
First: Main Method should be always static.
Second: Because you are calling domainChatLimit() from Main(static) than it should be also static
Third: Because you used firstName, lastName attributes in a static method domainChatLimit() then they should be also static
Fourth: Scanner should be also static because you are using it to get firstName, lastName and they are both static.
NOTE: There is no need to define a new instance of this class to call an internal method
Solution should be like below (tested successfully):
import java.util.Scanner;
public class Program{
// variables below should be defined as static because they are used in static method
static Scanner read = new Scanner(System.in);
static String firstName = read.nextLine();
static String lastName = read.nextLine();
// Main method is static
public static void main(String[] args) {
//There is no need to define a new instance of this class to call an internal method
domainCharLimit();
}
// calling from main static method so it should be static
public static void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
if you want to create a Generic Util for that functionality you can do below logic:
PogramUtil.java
import java.util.Scanner;
public class ProgramUtil {
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
now you can call this way :
Program.java
public class Program{
// Main method is static
public static void main(String[] args) {
ProgramUtil programUtil = new ProgramUtil();
programUtil.domainCharLimit();
}
}

Writing a method to return the string inside an object in Java

I'm really new to Java and programming in general (~3 weeks of experience) so sorry if this question is obvious for you guys. I tried searching for answers here but couldn't find any that fit my specific problem. And yeah it's for school, I'm not trying to hide it.
Here I'm supposed to write an object method that returns the string contained in the object oj, in reverse. I do know how to print a string in reverse, but I don't know how I should call the object since the method isn't supposed to have any parameters.
import java.util.Random;
public class Oma{
public static void main(String[] args){
final Random r = new Random();
final String[] v = "sininen punainen keltainen musta harmaa valkoinen purppura oranssi ruskea".split(" ");
final String[] e = "etana koira kissa possu sika marsu mursu hamsteri koala kenguru papukaija".split(" ");
OmaMerkkijono oj = new OmaMerkkijono(v[r.nextInt(v.length)] + " " + e[r.nextInt(e.length)]);
String reve = oj.printreverse();
System.out.println(reve);
}
}
class OmaMerkkijono{
private String jono;
public OmaMerkkijono(String jono){
this.jono=jono;
}
public String printreverse(){
//so here is my problem, i tried calling the object in different ways
//but none of them worked
return reversedstringthatdoesnotexist;
}
}
You just need to add this to your "printreverse" method :
new StringBuilder(this.jono).reverse().toString()
With this, when you call the method with the object "oj":
String reve = oj.printreverse();
After the previous line, "reve" must contain the value of the String reversed.
Olet hyvä, moi moi!
To revers a String use StringBuilder and reverse()
public String printreverse(){
return new StringBuilder(jono).reverse().toString();
}
To access private attributes from outside the class you use what are called accessors and mutators, aka getters and setters.
You just need a basic getter that also reverses the string.
public class MyObject {
private String objectName;
MyObject(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName; // returns objectName in order
}
public String getReversedObjectName() {
return new StringBuilder(objectName).reverse().toString();
}
public static void main(String[] args) {
MyObject teslaRoadster = new MyObject("Telsa Roadster");
System.out.println(teslaRoadster.getObjectName());
System.out.println(teslaRoadster.getReversedObjectName());
}
}
Output:
Telsa Roadster
retsdaoR asleT

Return a string value to the pass-in varibale from the argument in a function

I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

How to print a String defined in one class in a different class?

I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}

Categories

Resources