I can see you are probably quite new to Java - so you may be lacking a few fundamentals.

Probably best to just pass the string in as a parameter to the method in your case e.g.

public void WelcomeAgent(String lastName) {

and when you call the method, send that value in e.g.

AgentObject.WelcomeAgent(userinput);    

Btw, a few convention tips. Variables and functions should start with a lower case . e.g.

String lastName;

and

Citizen citizen = new Citizen();
Answer from Bruce Lowe on Stack Overflow
Top answer
1 of 3
3

If you're trying to call a variable from another class, you have several options:

1) Declare the variable in the other class as static:

public class Estadisticas {

  public static String c1 = "Tu personaje";
  ...
}

So in the other class, you can just call the string like so:

public class Start extends Estadisticas {
  public static void main() {
    System.out.println(Estadisticas.c1);
  }
}

2) Have the stats method return the string:

public String stats() {

  final String c1 = "Tu personaje";
  final int Nivel = 1;
  final int Salud = 50;
  final int Ataque = 2;
  final int Defensa = 1;

  final String c2 = "Primer monstruo - Rata rabiosa";
  final int SaludM1 = 2;
  final int AtaqueM1 = 1; 

  return c1;
}

So you can do this:

public class Start extends Estadisticas {
  public static void main() {
    Estadisticas es = new Estadisticas();
    System.out.println(es.stats());
  }
}

3) Use an accessor method and instance variables:

public class Estadisticas {
  private String c1, c2;
  private int nivel, salud, ataque, defensa, saludM1, ataqueM1;

  public void stats() {
    c1 = "Tu personaje";
    nivel = 1;
    salud = 50;
    ataque = 2;
    defensa = 1;

    c2 = "Primer monstruo - Rata rabiosa";
    saludM1 = 2;
    ataqueM1 = 1; 
  }

  //accessor method
  public String getc1() {
    return c1;
  }
}

So in the other class you can use:

public class Start extends Estadisticas {
  public static void main() {
    Estadisticas es = new Estadisticas();
    System.out.println(es.getc1());
  }
}
2 of 3
0

Like this :

public class Estadisticas {
    final String c1 = "Tu personaje";
    final int Nivel = 1;
    final int Salud = 50;
    final int Ataque = 2;
    final int Defensa = 1;

    final String c2 = "Primer monstruo - Rata rabiosa";
    final int SaludM1 = 2;
    final int AtaqueM1 = 1; 

    public void stats() {

    }
}

public class Start extends Estadisticas {
    public static void main() {
     Estadisticas  es = new Estadisticas (); // create instance here
        System.out.println(es.c1);  // print using the instance


    }

}
🌐
Stack Overflow
stackoverflow.com › questions › 32110614 › calling-a-string-value-from-one-class-to-another-class
java - Calling a String value from one class to another class - Stack Overflow
class CreateFamily{ private String name; public String getName(){ return name; } public void setName(String name){ this.name=name; } } Now you need to get this name string in another class say ParentSearchProcess:-
Top answer
1 of 4
1

I want the user input from this class and bring into another class and use the number variable for a If statement.

It is simple take a look at below example(make sure to add both classes in one package different java files as Player.java and ExampleClass.java),

This is the class that Scanner has:

import java.util.*;

public class Player{
    public static void main (String [] args){

        Scanner getInput = new Scanner(System.in);
        System.out.print("Input a number");
        //you can take input as integer if you want integer value by nextInt()
        String number = getInput.nextLine();

        ExampleClass obj = new ExampleClass(number);
        obj.checkMethod();
    }
}

This is the class that check number:

public class ExampleClass{
    int number;
    public ExampleClass(String number){
        try{
            //If you want to convert into int
            this.number = Integer.parseInt(number);
        }catch(NumberFormatException e){
            System.out.println("Wrong input");
        }
    }

    public void checkMethod(){
        if(number > 5){
            System.out.println("Number is greater.");
        }else{
            System.out.println("Number is lesser.");
        }
    }
}

Few thing to mention:

Your example code contains syntax errors, fix those first.

  1. If you want integer you can use getInput.nextInt() rather than getInput.nextLine().
  2. You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
  3. Use proper naming convention.
  4. In my example I convert the String into integer inside the constructor and wrap with try-catch block to prevent from NumberFormatException(If you input character or something you can see wrong input will print). Sometimes in variaus situation it is not good to use try-catch in constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.
2 of 4
0

Where you normally make an import on the other class, just import the Player class and it should work

Top answer
1 of 2
3

It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.

You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:

class CharacterSurvey {
    public String takeSurvey() {
        //ask questions, score points
        String character = null;

        if(firstPerson == outcome) {
            character = "First Person";
        }

        return character;
    }
}

Now, when you call this method, you can retrieve the value returned from it:

class Main {
    public static void main(String[] args) {
        CharacterSurvey survey = new CharacterSurvey();

        String character = survey.takeSurvey();
        System.out.println(character);
    }
}
2 of 2
1

There are several mistakes here.

First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work

public void survey(String character)

Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as

public String survey() {} 

this method returns a string now.

If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.

By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).

Hope this helped

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 22039952 › how-to-get-a-string-variable-from-another-class
java - How to get a string variable from another class - Stack Overflow
Copypublic class write { //public static String getar=get.ar[1]; //getar = get.ar[]; public static void main(String args[]) throws IOException { New_string file = new New_string(); file.read() //site.readline System.out.println(file.S1); //String S1 = ar[1]; } } Copyimport java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; public class New_string { public static String S1; public static int a=0; public static String ar[]; public static int lnum=0; public static String line=null; public read(String args[]) throws IOException { FileReader fr= new FileReader("read_listflow.txt"); BufferedReader br=new BufferedReader(fr); while ((line=br.readLine())!=null) { lnum=lnum+1; } FileReader fr1= new FileReader("read_listflow.txt"); BufferedReader br1=new BufferedReader(fr1); ar=new String[lnum]; while ((line=br1.readLine())!=null) { ar[a]=line; a=a+1; } S1 = ar[1]; } }
🌐
Stack Overflow
stackoverflow.com › questions › 10049278 › how-to-get-a-string-from-one-class-to-another
java - How to get a string from one class to another - Stack Overflow
Is it possible that anyone can suggest how to get the name from the plane class to the airport class please. ... @aishwarya Just want to point out that you must extend Observable, since it's a class, not an interface.
🌐
Stack Overflow
stackoverflow.com › questions › 27989928 › getting-string-info-from-another-java-class-rather-than-the-same-one
Getting String info from another java class rather than the same one - Stack Overflow
That's done but now I need the string to be obtained from my other class. Here is where my question lies, How do I do that if my code looks like this: import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class SwingJPanelDemo extends JFrame { //where I want the string to be send t
🌐
Stack Overflow
stackoverflow.com › questions › 43917285 › getting-strings-from-other-classes
java - getting strings from other classes - Stack Overflow
i use the String apkName and ... into my download method. ... public static class Stringz{ public String APK() { return apkNames; } public String FILEPATH() { return mCurrentPhotoPath; }...
🌐
Stack Overflow
stackoverflow.com › questions › 32074694 › java-get-string-value-from-class1-and-call-to-the-other-class2
JAVA: get String value from Class1 and call to the other Class2 - Stack Overflow
public class MainForm extends JFrame { private String username; public MainForm(String username){ this.username = username; //you set the value of your label to username // here or somewhere else in your form mLabel.setText(username); } } ... Fixed typo. Should be getString ... yes, I recognize it... but still error... I think the resultSet thing... I manage to make another ResultSet but still error...
🌐
Coderanch
coderanch.com › t › 543220 › java › Passing-variable-class
Passing a variable from one class to another (Beginning Java forum at Coderanch)
June 27, 2011 - If the String you are trying to get is a constant and can be declared something like this: then you can use: If you want to be able to read the string value, say from a file or when you start the program, you could use the Singleton pattern to give your other classes access to the value. But then again, Singeltons are EVIL!! So, another solution would be to use an interface that holds your static variables and have all the classes that needs the variable implement it.
🌐
Coderanch
coderanch.com › t › 697614 › java › pass-string-class-man-class
how to pass string to another class man class (Beginning Java forum at Coderanch)
I've manage to pass string between classes if i pass it to void method using setter and getter it seems i cannot implement it in main class. can you help me? i'm sorry if it's basic question. thanks My First program : My second program : ... Make first() return the string. ... Also, at line 3 of SecondProgram, create an instance of FirstProgram and call first() from it.
Top answer
1 of 7
16

Both techniques are terrible, but using the getter is the common (and safer) practice.

In order to access a public data member (a.k.a. public field or public property) of a class, you must know the implementation details of the class (the data member name and the data member type). This is a bad thing; it breaks the OOP concept "information hiding" and increases "coupling".

Using a getter is also bad (as in a bad OOP practice) because objects are not just wrappers around data; objects are supposed to encapsulate functionality and data. "store this here value so I can get it later" is not functionality; it is hoot functionality (as in a monkey in a cage hooting). Getters are; however, an accepted practice in java (and other OOP-lite languages like c++ and c#).

Lest you think I am some ivory tower purest, of course I use getters; I use java, so I use getters.

Getters are fine for getting the work done (no pun), just don't walk around believing that "I R gud OOP Prgmr", because if you use getters you are not a "good oop programmer", you are just a programmer who gets work done.

Edit: Perhaps a better way.

The better way is to not use getters, but to instead design your classes so they expose functionality not data. In practice, there is a point where this breaks down; for example, if you need to display an address on a JSP page, you put a bean in the request (or session or blah) with the address and expose the values using getters. A "more oop pure" way would be to put a bean that exposed "display the address on a jsp" functionality.

Edit2: Perhaps a better example.

Say I work for a phone company, in the USA, and I have an object that represents a customers phone number. This might look like the following:

public class CustomerPhoneNumber
{
  private String npa; // numbering plan area (google search nanp for more details)
  private String nxx; // exchange.
  private String serviceNumber;

  public String toString()
  {
    return "(" + npa + ") " + nxx + "-" + serviceNumber;
  }

  public boolean equals(Object object)
  {
    ... standard equals implementation (assume this works)
  }
}

Now say I get a phone number as an input from a web page in the form String inputPhoneNumber. For the purposes of discussion, the class that receives this input is called "the servlet".

How can I answer this question: "Is the input phone number in my list of CustomerPhoneNumber objects?"

Option 1 is make the npa, nxx, and serviceNumber data members public and access them. This is terrible.

Option 2 is provide getters for npa, nxx, and service number and compare them with the input. Also terrible, too many internal details exposed.

Option 3 is provide a getter that returns the formatted phone number (I called this toString() above). This is smarter but still terrible because the servlet has to know the format that will be used by the getter and ensure that the input is formatted the same way.

Option 4 (I call this "Welcome to OOP") provide a method that takes a String and returns true if that matches the customer service number. This is better and might look like this (the name is long, but sufficient for this example):

public boolean doesPhoneNumberMatchThisInput(final String input)
{
   String formattedInput;
   String formattedCustomerPhoneNumber = npa + nxx + serviceNumber;

   formattedInput = ... strip all non-digits from input.

   return StringUtils.equals(formattedCustomerPhoneNumber, formattedInput);
}

This is the winner because no implementation details are exposed. Also the toString can be used to output the phone number on a JSP page.

StringUtils is part of Apache Commons Lang.

2 of 7
8

For the sake of encapsulation you should always go with the second alternative.

myLocalVar = myClass.getMyVarVal();

Efficiency wise you most likely won't notice a difference.

Top answer
1 of 4
1

I think you misunderstood the main method, maybe I am wrong, however only one main method is executed.

If you run Sample2.main - on Sample1 you are not setting a name so it is null (Sample1.main is never executed).

If you run Sample1.main - Sample1 is created and assigned a name.

So either assign the name in the Sample2.main:

public static void main(String[] args) {
  Sample1 n2= new  Sample1();
  n2.setName("xxx");
  System.out.println(n2.getName());
}

or do it via constuctor.

public class Sample1 {
  private final String name;
  public String getName() {
    return name;
  }
  public Sample1(String name) {
    this.name = name;
  }
}
2 of 4
1

Consider the code :

Sample1 n2= new  Sample1();
System.out.println(n2.getName());

Here the Name is not set , So you need to set the name before getting the name.

Sample1 n2= new  Sample1();
n2.setName("name goes here");
System.out.println(n2.getName());

Also, you can try parameterized constructor in the Sample1 class and access like in sample2 class:

Sample1 n2= new  Sample1("your name goes here");
System.out.println(n2.getName());

The constructor will be :

public Sample2(String name){
this.name = n;
}

3 thing you can add method in Sample1 class and access it in Sample2 class.

I don't want to set String value in Sample2 class, need to assign string value in Sample1 only, after that i need that string value in Sample2 class

    public class Sample1 {
    private String _name;
    public String getName() {
        return _name;
    }
    private setName(String name) {
        _name = name;
    }
    public SetNameHelper(){
       setName("somestring");//You will be setting the name in Sample 1
    }
}


public class Sample2 {
    public static void main(String[] args) {
        Sample1 n2= new  Sample1();
        n2.SetNameHelper();
        System.out.println(n2.getName());//You will be getting Name in Sample 2 class
    }
}