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 OverflowI 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();
Do you want to access the value of LastName in class Agent ?
What if you change it like this
public class Login {
String FirstName, LastName;
public void LoginScreen() {
Agent AgentObject = new Agent();
Citizen CitizenObject = new Citizen();
....
LastName = input.next();
...
}
public String getLastName()
{ return LastName; }
and in class Agent
you can use LoginObject.getLastName() to get the it.
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());
}
}
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
}
}
The default scope is package-private. Use the public modifier on the String declaration
public String productId;
The only reason of this behavior is that you declared yours class Strings as package-protected strings. In Java this means, that this fields will be accessible only for classes in the same package.
There are several solutions for your problem. The first (and the worst) - declare your fields as public strings, like this:
public String myField;
The second - create getters for your fields and declare your strings as private fields, like this:
private String myField;
public String getMyField() {
return myField;
}
Then, use this getters on your class object.
Hope, it helps.
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.
- If you want integer you can use
getInput.nextInt()rather thangetInput.nextLine(). - You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
- Use proper naming convention.
- In my example I convert the
Stringinto integer inside the constructor and wrap withtry-catchblock to prevent fromNumberFormatException(If you input character or something you can seewrong inputwill print). Sometimes in variaus situation it is not good to usetry-catchin constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.
Where you normally make an import on the other class, just import the Player class and it should work
I'm a bit confused on what is being asked but I'll try to answer.
I would declare the field private String senderNum and the method public String getSenderNum(){return senderNum;} and remove the declaration of String in:
String senderNum = phoneNumber;
message = currentMessage.getDisplayMessageBody();
then in MainActivity.java call getSenderNum() where it is needed.
One way I see is create a new class that extends the class which has the
public void onReceive(Context context, Intent intent)
method. Now in this class declare senderNum as an instance variable. Make it's getter and setter method. Infact you can make it static if it is same across all the instances. Then set this new class as a listener(whichever it is) to the instamce of IncomingSms class. Then you can use getter/setter ot directly reference using class name if static.
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);
}
}
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
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.
There is no need to pass array to , since ActivityTo is also an activity so can fetch the resources array here too
public class ActivityTo extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = getListView();
myview.setAdapter(adapterCityBreak);
}
}
To remove current error,
either do this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con=this;
}
or
use this in MainActivity because con is not initialized
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
instead of
String [] arrayCityBreak = con.getResources().getStringArray(R.array.citybreak);
My application shuts down when i click the button to get to the new intent. It is because of the String[] i try to send, but I don't see why is won't work.
It is caused by this con, because the context is null:
Context con;
Use this like:
String [] arrayCityBreak = this.getResources().getStringArray(R.array.citybreak);
or
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
If I understood your question, you have an activity that gets some information and wanna use them in another activity. so you can use intents like this code in the first activity when you want to go to second class:
Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("value", "some string");
startActivity(i);
in second activity use this code:
Bundle extras = getIntent().getExtras();
// get data via the key
String value1 = extras.getString("value");
you can have extras as many as you want
I think you can just put them in Intent:
Pass a String from one Activity to another Activity in Android
or use Bundle: https://developer.android.com/reference/android/os/Bundle.html
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.
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.
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;
}
}
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
}
}