简体   繁体   中英

How to Modify Another Object in Another Class in Java?

I'm new to Java, and am confused when reading other solutions to this problem. Can I get some layman's terms to how to do this in my case?

I'm making a program that will take information from a student and be able to print out a full report or print out a full name of the student.

I'm using BlueJ to write my code.

Here is what I have so far for my first class that takes in the information.

import java.util.Scanner;

public class StudentData2 {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args){

    long student_id;
    String firstName;
    String lastName;
    String classification;
    String fullGender = "none";
    char gender = 'n';
    double gpa = 0.0;


    switch (fullGender.toLowerCase()) {
        case("female"): gender = 'f';
            break;
        case("male"): gender = 'm';
            break;
        default: System.out.println("That's not a selectable gender.");
    }


    boolean isPassing;

    if (gpa > 2.0) {
        isPassing = true;
    }else {
       isPassing = false;
    }

    char averageGrade;

    if (gpa == 4.0) {
        averageGrade = 'A';
    }
        if(gpa >= 3.0){
            averageGrade = 'B';
        }
            if (gpa >= 2.0){
               averageGrade = 'C'; 
            }
                if (gpa >= 1.00) {
                    averageGrade = 'D';
                }else{
                        averageGrade = 'F';}


        }
    }

Now I want to make another class called 'StudentData2Demo', and I want it to print out some questions, and then whatever is input into the terminal, it puts that into the value of the objects in the other class.

Here is what I have so far.

import java.util.Scanner;
public class StudentData2Demo{
public static void main(String[] args) {
    StudentData2 student = new StudentData2();

   System.out.println("What is your First Name?");
    student.firstName = input.next();


}
}

Yet, when I try to reference the 'input' scanner I made in the other class, it says it can't find that variable. This is also the same for firstName, and likely the rest when I type those in.

Help?

remove the main() from your student class... it should be something along the following lines.

public class StudentData2 { 

//remove the main()... you execute the main in demo, not here.

//you store your student data here
long student_id;
String firstName;
String lastName;
String classification;
String fullGender = "none";
char gender = 'n';
double gpa = 0.0;
boolean isPassing = false;
char averageGrade ='?';
//recommend to put all the fields at the top (easier to see)

//you can create methods to change the parameters in the class 
public boolean setGender(){ 

    Scanner input = new Scanner(System.in);

    System.out.println("Enter gender (male/female):");
    fullGender = input.next(); //you get the input from keyboard
    switch (fullGender.toLowerCase()) {
           case("female"): gender = 'f';
        return true;
           case("male"): gender = 'm';
        return true;
        default: System.out.println("That's not a selectable gender.");
           fullGender ="none"; //reset it back to default.
           return false;
}

//same idea for creating methods for the other  fields like grades.

public boolean setGrades(){

    Scanner input = new Scanner(System.in);

    System.out.println("Enter grades:");
    gap = input.nextDouble(); //remember to do your Exception check here !!

    isPassing = (gpa > 2.0); // no need if else loop here.
                             //anything more than 2 is true.


    if (gpa == 4.0) {
        averageGrade = 'A';
    }
    else if(gpa >= 3.0){ // we use an else if here... 
                         //if not it'll get replaced.
        averageGrade = 'B';
    }
    else if (gpa >= 2.0){
        averageGrade = 'C'; 
    }
    else if (gpa >= 1.00) {
        averageGrade = 'D';
    }else{
        averageGrade = 'F';  
    }
}//close bracket for method setGrades()
}//close bracket for class

to update the fields in your demo class, just call

 boolean isGenderValid = student.setGender(); //the idea is encapsulation 
                                              // you hide the implementation detail away from the caller.

 //you can set grades similarly
student.setGrades();

to access the field, you can use

System.out.println("student's gender is " + student.fullGender);

Welcome to StackOverflow and Java!

Edit: I don't believe giving you exact code would help you solve your issue without raising a hundred more. And since you asked for layman's terms, I'll just briefly explain why you're having an issue :)

The beauty of Java (and object-oriented programming in general) is that everything is separated. That is a blessing and a curse. You have one class (also called an object) called StudentData2 , that gets the information from the student using a Scanner object.

That Scanner "belongs" to the StudentData2 class. No one else can use it, see it, or even knows it exists. So when you create your StudentData2Demo class, you are basically starting fresh. This new class only knows about variables and fields that are within its own file.

Now, in Java, there are a lot of ways that you can pass data from one class to another, and it is definitely possible to be able to use your Scanner in both classes, but I highly recommend doing a little more study on object-oriented programming. The concepts are extremely powerful and therefore require a bit of learning to really understand them.


Further Help

I am not paid by any of these resources, but as a fairly new developer myself, I do have some recommendations.

First of all, I used a great online course to learn Java programming. Tim Buchalka teaches a very in depth course on Java that starts at the very beginning but progresses to advanced topics. You can find his Complete Java Masterclass here .

Also, BlueJ is great for very small projects, but I do recommend a full Java IDE if you plan to progress beyond the basics. IntelliJ IDEA is not only free, but also a bit more mature than Eclipse or Netbeans , but feel free to choose whichever you are most comfortable with.

This is happening because the fields you are trying to access are not direct members of the class. To resolve this issue, you need to make some changes in the StudentData2 class There is no need for the main method.

import java.util.Scanner;

public class StudentData2 {
public long student_id;
public String firstName;
public String lastName;
public String classification;
public String fullGender = "none";
public char gender = 'n';
public double gpa = 0.0;
}

After this add rest of the code in a method. Make sure you make the access modifier as public .

Now you can use the student object in the second class to set the properties and call the methods.

  1. Your StudentData2 class should be model class ideally and all logic should go in processing class.

  2. Two main method indicate two different path, there is no need of main method in StudentData2.

  3. To directly answer your exact question, 'to modify another object you have to have reference of that object'. Here you don't have it since you have not created object on StudentData2

You program should look some what like this.

public class StudentData {

private long studentId;
private String firstName;
private String lastName;
private String classification;
private char gender;

public long getStudentId() {
    return studentId;
}


public void setStudentId(long studentId) {
    this.studentId = studentId;
}


public String getFirstName() {
    return firstName;
}


public void setFirstName(String firstName) {
    this.firstName = firstName;
}


public String getLastName() {
    return lastName;
}


public void setLastName(String lastName) {
    this.lastName = lastName;
}


public String getClassification() {
    return classification;
}


public void setClassification(String classification) {
    this.classification = classification;
}


public char getGender() {
    return gender;
}


public void setGender(char gender) {
    this.gender = gender;
}


@Override
public String toString() {
    return "StudentData [studentId=" + studentId + ", firstName="
            + firstName + ", lastName=" + lastName + ", classification="
            + classification + ", gender=" + gender + "]";
}    

}

And the Demo class as

import java.util.Scanner;

public class StudentDemo {

public static void main(String[] args) {

    StudentData data = new StudentData();
    Scanner input = new Scanner(System.in); 
    boolean valid = true;
    String temp = "";

    while(valid){
        System.out.println("What is student ID:");          
        temp = input.nextLine();
        try {
            long id = Long.parseLong(temp);
            data.setStudentId(id);
            valid = false;
        }
        catch(NumberFormatException exception){
            System.out.println("Invalid student id.");
            continue;
        }                       
    }

    temp = "";      
    valid = true;
    while(valid){
        System.out.println("What is student First name:");          
        temp = input.nextLine();
        if(!temp.isEmpty()){
            data.setFirstName(temp);                
            valid = false;
        }
        else{
            System.out.println("First name cannot be empty.");
        }
    }

    temp = "";      
    valid = true;
    while(valid){
        System.out.println("What is student Last name:");           
        temp = input.nextLine();
        if(!temp.isEmpty()){
            data.setLastName(temp);             
            valid = false;
        }
        else{
            System.out.println("Last name cannot be empty.");
        }
    }

    temp = "";  
    valid = true;
    while(valid){           
        System.out.println("What is student gender:");
        temp = input.nextLine();
        switch (temp.toLowerCase()) {
            case("female"):
            case("f"):
                data.setGender('f');
                valid = false;
                break;
            case("male"): 
            case("m"):
                data.setGender('m');
                valid = false;
                break;
            default: 
                System.out.println("That's not a selectable gender. Please select from f/m.");
        }
    }

    temp = "";  
    valid = true;
    while(valid){
        System.out.println("What is student gpa:");         
        temp = input.nextLine();
        try {
            double gpa = Double.parseDouble(temp);              
            valid = false;

             if (gpa >= 4.0) {
                 data.setClassification("Passed with A");
             }
             else if(gpa >= 3.0){
                 data.setClassification("Passed with B");
             }
             else if (gpa >= 2.0){
                 data.setClassification("Passed with C");
             }
             else if (gpa >= 1.00) {
                 data.setClassification("Failed with D");
             }
             else {
                 data.setClassification("Failed with F");
             }
        }
        catch(NumberFormatException exception){
            System.out.println("Invalid student gpa.");
            continue;
        }                       
    }       
    System.out.println("Student details you entered:"+ data.toString());
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM