简体   繁体   English

如何在Java的另一个类中修改另一个对象?

[英]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. 我是Java的新手,在阅读有关此问题的其他解决方案时感到困惑。 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. 我正在使用BlueJ编写代码。

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. 现在,我要创建另一个名为“ StudentData2Demo”的类,并希望它打印一些问题,然后将任何输入终端的内容都放入另一个类的对象的值中。

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. 这对于firstName也一样,当我键入它们时,其余的可能也一样。

Help? 救命?

remove the main() from your student class... it should be something along the following lines. 从您的学生班级中删除main()...应该遵循以下几句话。

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! 欢迎使用StackOverflow和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. Java(通常是面向对象的程序设计)的美在于,一切都是分离的。 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. 您有一个名为StudentData2类(也称为对象),该类使用Scanner对象从学生那里获取信息。

That Scanner "belongs" to the StudentData2 class. Scanner “属于” StudentData2类。 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. 因此,当您创建StudentData2Demo类时,您基本上是从头开始的。 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. 现在,在Java中,有很多方法可以将数据从一个类传递到另一个类,并且绝对有可能在两个类中都使用Scanner ,但是我强烈建议您对对象进行更多研究,面向程序设计。 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. 首先,我使用了很棒的在线课程来学习Java编程。 Tim Buchalka teaches a very in depth course on Java that starts at the very beginning but progresses to advanced topics. Tim Buchalka教授一门有关Java的非常深入的课程,该课程从一开始就开始,但逐步发展为高级主题。 You can find his Complete Java Masterclass here . 您可以在这里找到他的Complete Java Masterclass

Also, BlueJ is great for very small projects, but I do recommend a full Java IDE if you plan to progress beyond the basics. 另外, BlueJ非常适合非常小的项目,但是如果您打算超越基础知识,我建议您使用完整的Java IDE。 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. IntelliJ IDEA不仅免费,而且比EclipseNetbeans还成熟一些,但可以自由选择最适合的方式。

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. 若要解决此问题,您需要在StudentData2 class进行一些更改。不需要main方法。

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 . 确保将access modifier as public

Now you can use the student object in the second class to set the properties and call the methods. 现在,您可以在第二个类中使用Student对象设置属性并调用方法。

  1. Your StudentData2 class should be model class ideally and all logic should go in processing class. 理想情况下,StudentData2类应为模型类,并且所有逻辑都应进入处理类。

  2. Two main method indicate two different path, there is no need of main method in StudentData2. 两个主要方法表示两条不同的路径,在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 在这里您没有它,因为您尚未在StudentData2上创建对象

You program should look some what like this. 您的程序应该看起来像这样。

public class StudentData { 公共课程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; 导入java.util.Scanner;

public class StudentDemo { 公共课程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());
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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