it's print null in console when I run a program in Java - java

`
package Stuff;
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
studentName = name;
studentAge = age;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
`
I Don't Know where is the wrong in code the console print me (null) when i request student1.printName() and 0 When i request Student.printAge()

Your variable assignments in the constructor are the wrong way around.

You are assigning the variables in the constructor in wrong way. The correct way will be:
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
If you auto-generate the constructors then it will look like this, which is more common convention:
public Student(String name,int age){
this.name = name;
this.age = age;
}

You messed up the initialization part studentname = name and studentage = age the right way of initialization is given down
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}

The constructor should be like
public Student(String studentName,int studentAge){
this.name = studentName;
this.age = studentAge;
}

I highly recommend that you have a look at this article on associativity in Java.
Basically, when you assign a value to a variable using the = operator, the statement is carried out from right to left. Hence, the outcome of the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.
Hence, int a = 5+5 means that the outcome of 5+5 is stored in variable a. This is also why studentName = name assigns the value of name (which is the default value of the String type - null) to studentName.
It is also important to note that null is a keyword in Java, and if you print null like this:
System.out.println(null)
A Syntax Error will be thrown (which is for a different reason).
EDIT - At the time of typing this out, there was only one answer, and not explanatory in any way. Now, I see there are more. Although the other answers may tell you what to do, I figured that this answer would tell you how to think in Java, so that you make no such mistakes again.

Related

My getMethod does not return the value in the setMethod: Java

public class OOP_10_Encapsulation {
private String firstName;
private String favFood;
private int age;
private float weight;
//create a set method for firstName
public void setFirstName(String firstName){
this.firstName = firstName;
}
//create a get method for firstName
public String getFirstName(String firstName){
this.firstName = firstName;
return firstName;
}
//create a set method for favFood
public void setFavFood(String favFood){
this.favFood = favFood;
}
//create get method for favFood
public String getFavFood(String favFood){
this.favFood = favFood;
return favFood;
}
//create a set method for age
public void setAge(int age){
this.age = age;
}
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
//create a set method for weight
public void setWeight(float weight){
this.weight = weight;
}
//create a get method for weight
public float getWeight(float weight){
this.weight = weight;
return weight;
}
}
public class OOP_11_TestEncapsulation {
public static void main(String[] args) {
OOP_10_Encapsulation learner1 = new OOP_10_Encapsulation(); //create object of OOP_10_Encapsulation
learner1.setFirstName("Evander O A");
learner1.setAge(31);
learner1.setWeight(98.6F);
learner1.setFavFood("waakye");
System.out.println("Hi, my name is " + learner1.getFirstName());
}
}
I have this challenge that I am not able to get my head around. When I run the code in the main method, the get method does not return the name "Evander O A" as set in the set method. Actually, none of my get methods are getting anything I need them to get.
Let's look at one of your get methods:
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
The purpose of a get method, also called "getter" is to get something from inside an object, usually it's some of the object's attribute that you wanna get.
If you just want to get an attribute, there is no need to pass a parameter to the get method:
public int getAge(int age) // age parameter is useless
Not only that it is useless here, but you are also doing something wrong, in the get method you are first changing attribute's value. You are effectively doing a set inside a getter method:
this.age = age; // wrong
Given your code for getAge method, let's see how it will execute when you call something like:
System.out.println("Hi, my name is " + learner1.getAge())
The function getAge will be called with no parameter, although it is expecting one. So most probably you won't be able to compile this piece of code.
I got the following error when trying to compile something similar:
https://imgur.com/a/4AVwMke
So if you create a function with 1, 2, 3 or whatever number of parameters then you must call it using the same number of arguments to the function call. Otherwise most probably that code won't run.
Now let's assume I call it with some value as argument, probably you did too.
System.out.println("Hi, my name is " + learner1.getAge(0))
This is going to happen:
//create a get method for age
public int getAge(int age // which is 0){
this.age = age; // you set the age to 0, losing the old value
return age; // you return 0, because you no longer have the old value
}
How should you do it? Simple:
//create a get method for age
public int getAge(){
return age;
}
Now apply this fix to all of your getters (the get methods) and you are good to go. Let me know if something is not clear.

Using Eclipse, trying to get a program to work

I am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding

Why can't my class members access my getter methods?

I have these two files, personalinfo.java which defines the personalInfo class, and testpersonalinfo.java which tests the class. When I try to access my getter methods from testpersonalinfo.java I receive an error that these methods are undefined. Can anybody please tell me why?
personalinfo.java:
public class personalInfo {
private String name;
private String address;
private int age;
private long phoneNumber;
personalInfo(){
name = "Default Name";
address = "Default Address";
age = 100;
phoneNumber = 0000000000;
}
personalInfo(String nam, String add, int ag, int phone){
name = nam;
address = add;
age = ag;
phoneNumber = phone;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getAge(){
return age;
}
public long getPhoneNumber(){
return phoneNumber;
}
public void setName(String nam){
this.name = nam;
}
public void setAddress(String add){
this.address = add;
}
public void setAge(int ag){
this.age = ag;
}
public void setPhoneNumber(long phone){
this.phoneNumber = phone;
}
}
testpersonalinfo.java:
import java.util.Scanner;
public class personalInfoExample {
public static void main(String[] args){
personalInfo[] pers = new personalInfo[3];
Scanner input = new Scanner(System.in);
String inName;
String inAddress;
int inAge;
long inPhoneNumber;
for(int i=0; i<3; i++){
pers[i] = new personalInfo();
System.out.printf("Please input the name for person %s: ", i );
inName = input.nextLine();
pers[i].setName(inName);
System.out.println(pers[i].getName);
System.out.printf("Please input the address for person %s: ", i );
inAddress = input.nextLine();
pers[i].setAddress(inAddress);
System.out.println(pers[i].getAddress);
System.out.printf("Please input the age for person %d: ", i );
inAge = input.nextInt();
pers[i].setAge(inAge);
input.nextLine();
System.out.println(pers[i].getAge);
System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
inPhoneNumber = input.nextLong();
pers[i].setPhoneNumber(inPhoneNumber);
System.out.println(pers[i].getPhoneNumber);
input.nextLine();
}
input.close();
}
}
The getters are functions, not fields; so to call them you need to use () (like in: pers[i].getAdress().
Also, class names should be capitalized, but it's not really important (just makes it easier to read.
As someone suggested in a comment, you should use an IDE, in case you are not doing it. The IDE will point you to the obvious little mistakes (both errors and convention mistakes) like the ones above, and save you a long time. If you don't know where to get started for that, search Eclipse or Netbeans. (Eclipse is my personal favourite).
EDIT: I just saw Eran commented the answer to your error, so if he posts it as an answer accept his first.
in all your sysout statements you are trying to access getter without () this.
please try this
System.out.println(pers[i].getName()); //change all your getters
instead of
System.out.println(pers[i].getName);
because getName() is a method not a Variable so always you need to use open-close braces () just after the method name
(either you defining or calling) .
please change all these methods (methods which raise an compile-time Error).
System.out.println(pers[i].getName);
System.out.println(pers[i].getAddress); //all these lines are causing of Compile time error.
System.out.println(pers[i].getAge);
System.out.println(pers[i].getPhoneNumber);
In case if you don't want to use getter method to access instance variable(Other than private variables) out side of the class defination, you can call instance variable-names directly on an instance object like
pers[i].name
For more on variables access control please refer java-doc

New to OOP, manage variables in classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}
According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");
I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.
Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.

returning a private static variable

I am having trouble returning my static private variable personCount. This variable simply counts the amount of people i add into my program, in my constructor for Person i set it so every time a person was entered, personCount incremented by 1. I have also created a getPersonCount method which simply returns the int value of personCount.
My problem is that when trying to implement this method in my test file, I am unsure on how to call the method, and get the value of personCount logged to the output.
I'm not sure if i am a million miles away or a small syntax error away, so any help would be much appreciated!
My Person constructor:
public Person(String foreName, String surName, int age,
double height, String gender)
{
this.foreName = foreName;
this.surName = surName;
this.age = age;
this.height = height;
this.gender = gender;
personCount = personCount +1;
}
My getPersonCount method:
public int getPersonCount()
{
return personCount;
}
My attempt to call the method in my test drive:
System.out.println(getPersonCount());
Please let me know if any more code is needed.
Try this, make your method definition in class Person like:
public static int getPersonCount() { //<-- note the static modifier
return personCount;
}
To invoke it:
System.out.println(Person.getPersonCount());//<-- use class name, if your using this method outside the class
You have two choices:
public static int getPersonCount() {
return personCount;
}
with the corresponding call:
Person.getPersonCount();
OR:
public int getPersonCount() {
return personCount;
}
and the corresponding call:
myPersonInstance.getPersonCount();
So in the last case, you deal with a Person instance.
public static int getPersonCount(){
return personCount;
}
Then invoke above method
Person.getPersonCount();

Categories

Resources