How to access string from one method in another - java

I have a method getMyName and want to access the String myName outside the method.
public String getMyName() {
setTestStart("Returning name");
String myName = getActiveName().getMyName();
setTestInfo("My name is: " + myName);
setTestEnd();
return myName;
}
I want to get a String myName result and use that result in other methods without constantly calling the whole getMyName method. How can i do that? Sorry for this silly question, I am new in Java.

you could put your var out of the all method scopes
public class Test{
private String myName; // it's out of all scopes and will can catch in all methods
public void getMyName(){
setTestStart("Returning name");
myName = getActiveName().getMyName(); // setting value
}
public void testMyNameInOtherMethod(){
setTestInfo("My name is: " + myName); // reading value. so important treating non-declaring and null values
setTestEnd();
}
// others methods...
}
you can use contructors to set values when init instances of new class as well

Related

Return the user input in another method from another class in Java

I have the following method in class Control:
public void addName() {
language.specifyArtist();
sc.nextLine();
}
and in class Artist:
public String getName (){
control.addName();
return artistName;
}
artistName is a data field. Somehow the user input given in the first method is not stored in the return value of the second method. Can somebody explain me how I have to set up the two methods that the first is handling the user input and the second is a getter for the user input?
First you have to return the result of sc.nextLine so that it can be assigned to the variable artistName:
public String readName() {
language.specifyArtist();
return sc.nextLine();
}
Also, the name should only be set once. This way I would not write the readName method into the get method. The simplest solution would be to call it in the constructor:
public Artist(Control control) {
artistName = control.readName();
}
public String getName() {
return artistName;
}
It would be nicer to pass the name directly in the constructor and thus separate the data from the input:
public Artist(String name) {
artistName = name;
}

Returning the updated variable passing through private methods

I noticed a scenario today. When we pass a parameter on private methods, the entity will return the revised values but not primitives.
Here is my sample code,
/**
* #author gowthami
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
String s = "gowth";
System.out.println("before " + s);
concateMe(s, "ami");
System.out.println("after " + s);
BeanTest bt = new BeanTest();
bt.setId("1");
System.out.println("before");
System.out.println(bt.getId());
System.out.println(bt.getName());
setBeanTestName(bt, "gowthami");
System.out.println("after");
System.out.println(bt.getId());
System.out.println(bt.getName());
String st = new String("gowth");
System.out.println("before " + st);
concateMe(st, "ami");
System.out.println("after " + st);
}
private static void setBeanTestName(BeanTest bt, String string) {
bt.setName(string);
}
private static void concateMe(String s, String string) {
s = s+string;
System.out.println("inside method " + s);
}
}
BeanTest.java
public class BeanTest {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So the bean is getting updated even though we are not returning it from private method but a string is not. Can someone explain me whats happening on JVM level?
This is because Java follows Call by value, not Call by reference.
When you are passing s you are actually passing value of s, not the actual s. So though you are changing s in concateMe(), it will not change in your main method.
When you are passing bt, then the change is affecting as you are changing the field variable of that reference. But if you change the reference, then there will be no effect. You can add this in main method:
System.out.println("before......");
System.out.println(bt.getId());
System.out.println(bt.getName());
changeBeanTest(bt);
System.out.println("after");
System.out.println(bt.getId());
System.out.println(bt.getName());
Suppose your changeBeanTest is like this:
private static void changeBeanTest(BeanTest tempBeanTest) {
BeanTest bt = new BeanTest();
bt.setId("2");
bt.setName("Trump");
tempBeanTest = bt;
}
run this. There will be no change to bt sent from main().
The Bean is a full object in java passed by reference to the private method so it is the same instance in the main method and the private method.
You are modifying the values of that instance so the changes show up in both places.
The string is more or less a primitive and passed as a copy of the value instead of the exact instance from main. It is a new instance in the private method and so you are modifying a new variable. The changes don't show up in the main method as it is a different entity.
String s = "gowth"; in this line s is pointing to "gowth" from String Pool.When you are calling
private static void concateMe(String s, String string) here String s is different from caller method String s.Here String s scope is local to method ContactMe,But contactMe local String s pointing same "gowth" which is pointed by Caller class String s.After s = s + string;since String is immutable the method local reference String s pointing a different String "gowthami",but caller method String s is still pointing to "gowth".So you are getting this output.
But in case of Bean both the object pointing same String reference,Once we made any change in reference it would be reflected for both object.

How to save a value of a private field (that was gotten in a method) in an object?

I can't figure out the way to save the supplierName value in a class object. I'm trying to change it in an addItem method using user input, and store it in a class object. It doesn't work. What am I doing wrong? Do I need to change my constructor? Or use a getter method?
Here is my code:
import java.util.Scanner;
public class PurchasedItem extends Item {
private String suppplierName;
public PurchasedItem() {}
#Override
public boolean addItem(Scanner input) {
super.addItem(input);
System.out.print("Enter the name of the supplier: ");
suppplierName = input.next();
return true;
}
#Override
public String toString() {
String str = super.toString();
return str + " Supplier: " + suppplierName;
}
}
A solution is to allow the constructor to take an argument such as:
public PurchasedItem(String constructorArgument){
supplierName = constructorArgument;
}
Then, you can do something like: PurchasedItem item = new PurchasedItem("some supplier");.
Since the class variable is private, you will also need getters/setters.
For instance:
Setter:
public void setSupplierName(String s){
this.supplierName = s;
}
Getter:
public String getSupplierName(){
return this.supplierName
}
Then to manipulate, you'd do something like:
item.setSupplierName("some company");
item.getsupplierName();
Though, you should be conscious of thread safety in regards to utilising setters.

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Simple ArrayList question

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Categories