How can I use a method to change a value? [duplicate] - java

This question already has answers here:
Can I pass parameters by reference in Java?
(8 answers)
Closed 8 years ago.
class Trial {
static void main() {
int i = 0;
change(i);
System.out.println(i);
}
static void change(int n) {
n = n + 2;
}
}
Output I'm getting - 0
Output I want - 2
Please help me change my code.

Everything in Java is pass by value:
http://www.javaranch.com/campfire/StoryPassBy.jsp
Try this instead:
class Trial {
static void main() {
int i = 0;
i = change(i);
System.out.println(i);
}
static int change(int n) {
return n + 2;
}
}
Edit
A parameter to a method is given a copy of the value. This value will either be a raw value (primitive) or an object reference (object).
For objects, a copy of the reference means you can change the state of an object within a method. What you cannot do is change the state having changed what the parameter is referring to.
Example 1:
class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
}
Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output Changed
...
public void changeName(Person person) {
person.setName("Changed");
}
Example 2:
Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output James
...
public void changeName(Person person) {
person = new Person(); // person is now referring to new object, not the one passed
person.setName("Changed");
}

Related

I'd like to set and get instance properties with methods in a class

I am a beginner of Java. I have a question.
Foo.java
public class Foo {
private String name;
private int num;
Foo(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return this.name;
}
public int getNum() {
return this.num;
}
public void setName(String name) {
this.name = name;
}
public void setNum(int num) {
this.num = num;
}
}
Main.java
public class Main {
public static void main(String[] args) {
String name = "Tom";
int num = 60;
Foo bar = new Foo(name, num);
}
}
Instead of this typical style of class on Java, I'd like to set and get instance properties with getter() and setter() method like...
public void setter(String p) {
this.p = p;
}
public String getter(String q) {
return this.q
}
I know these don't work, but I want to write Java method like following these codes in Python.
setattr(self, key, val)
getattr(self, key)
Would you please give me some pieces of advices?
Java does not support properties.
The only way to do this is through accessor and mutator (get/set) methods like you did at the top.
See: does java have something similar to C# properties?
What you want to achieve can be done using reflection as next:
// get the field "key" from the class "Foo"
Field field = Foo.class.getField("key");
// make it accessible as it is a private field
field.setAccessible(true);
// set the value of this field to val on the instance self
field.set(self, val);
More details about reflection here

Finding and removing an object from arraylist while not knowing the object's variables

I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar

Value added to array is NULL?

In my code below, I am experiencing a problem I am unable to get around... when I add a class Person object to an array, it appears to add fine, however when I attempt to print out that object value form a specified array position, it outputs "null."
Here is the code
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
System.out.println(Persons[i]);
}
Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
#Override
public String toString()
{
return name;
}
}
No, it hasn't added null to the array. It's put a reference to a Person object in the array, and when you call toString() on that Person object, it's returning the value of the name field... which is always null, because of this constructor:
public Person (String aName)
{
String name = aName;
}
That isn't assigning a value to the name field - it's declaring a local variable called name. (I'd expect a decent IDE to issue a warning about that.)
You want:
public Person (String aName)
{
name = aName;
}
The constructor
public Person (String aName)
{
String name = aName;
}
stores the name in a local variable.
Change this to
public Person (String aName)
{
this.name = aName;
}
The constructor is wrong
public Person (String aName)
{
String name = aName;
}
it is creating a new variable instead of assigning the field properly.
Try removing the type declaration:
public Person (String aName)
{
name = aName;
}

Print array variables, not variable pointer locations [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am working on a project from a Java text book, and I have come across an issue. I am attempting to print the variables in an array, however it continually prints the variables location (#hex code) instead of the actual variable... I believe I am attempting to print the array correctly via using a 'for loop'. I have attached my code below...
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
}
//Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
}
Any and all guidance is appreciated. Thank You!
You need to override the toString method in your Person class.
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName) { ... }
public String getName() { ... }
public int compareTo(Person o) { ... }
#Override
public String toString() {
return "My name is " + name; // For the example, you could return any String you want
}
}
the toString method is generally used to provide a description of the object.

Getting error while passing value to a constructor having return type void in java? [duplicate]

This question already has answers here:
What is wrong with my Code in relation to creating a constructor?
(3 answers)
Closed 8 years ago.
I am novice to java and trying to grasp the initial of the language. After going through a lecture on constructor, I am writing a program on that.
Name.java
public class Name
{
public static String f;
public static String l;
public void Name(String First,String Last)
{
f = First;
l = Last;
}
public String getName()
{
return f + " " + l ;
}
}
NameTest.java
public class NameTest
{
public static void main(String[] args)
{
Name myName = new Name("Mohammad","Shahjahan");
System.out.println(myName.getName());
}
}
Now an error is occured while running it..
NameTest.java:5: error: constructor Name in class Name cannot be applied to given types;
Name myName = new Name("Mohammad","Shahjahan");
^
required: no arguments
found: String,String
reason: actual and formal argument lists differ in length
1 error
If I change Name.java as follows, No error is occured.
public class Name
{
public static String f;
public static String l;
public Name(String First,String Last)
{
f = First;
l = Last;
}
public String getName()
{
return f + " " + l ;
}
}
Where is the error?
Constructors do not have return types, this
public void Name(String First,String Last)
{
f = First;
l = Last;
}
should be
public Name(String First,String Last)
{
f = First;
l = Last;
}
also your fields
public static String f;
public static String l;
should not be static,
public String f;
public String l;
The constructor shouldn't have a return type, so
public Name(String First,String Last)
{
f = First;
l = Last;
}
The error you're seeing is occurring because, not finding a constructor, java puts the default constructor in with no method body:
public Name(){}
So by trying to call new Name("firstName", "lastName"), It's telling you that the only existing constructor Name() can't accept two string inputs.
Also you should remove static from your fields. The fields firstName and lastName refer to a single Name object - making them static makes them refer to all Name object.

Categories