簡體   English   中英

如何在Java的另一個類中修改另一個對象?

[英]How to Modify Another Object in Another Class in Java?

我是Java的新手,在閱讀有關此問題的其他解決方案時感到困惑。 在我的情況下,我可以得到一些外行的條款嗎?

我正在制作一個程序,該程序將從學生那里獲取信息,並且能夠打印出完整的報告或打印出學生的全名。

我正在使用BlueJ編寫代碼。

到目前為止,這是我第一堂課所需要的信息。

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';}


        }
    }

現在,我要創建另一個名為“ StudentData2Demo”的類,並希望它打印一些問題,然后將任何輸入終端的內容都放入另一個類的對象的值中。

這是我到目前為止所擁有的。

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();


}
}

但是,當我嘗試引用我在另一類中制造的“輸入”掃描儀時,它說找不到該變量。 這對於firstName也一樣,當我鍵入它們時,其余的可能也一樣。

救命?

從您的學生班級中刪除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

要更新演示類中的字段,只需調用

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

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

要訪問該字段,您可以使用

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

歡迎使用StackOverflow和Java!

編輯:我不相信給您確切的代碼會幫助您解決問題而又不會籌集更多的錢。 既然您要求外行的條款,我將簡要解釋您為什么遇到問題:)

Java(通常是面向對象的程序設計)的美在於,一切都是分離的。 那是一種祝福和詛咒。 您有一個名為StudentData2類(也稱為對象),該類使用Scanner對象從學生那里獲取信息。

Scanner “屬於” StudentData2類。 沒有人可以使用,看到它甚至知道它的存在。 因此,當您創建StudentData2Demo類時,您基本上是從頭開始的。 這個新類僅了解其自己文件中的變量和字段。

現在,在Java中,有很多方法可以將數據從一個類傳遞到另一個類,並且絕對有可能在兩個類中都使用Scanner ,但是我強烈建議您對對象進行更多研究,面向程序設計。 這些概念非常強大,因此需要一些學習才能真正理解它們。


進一步的幫助

這些資源並沒有給我薪水,但是作為我自己一個相當新的開發人員,我確實有一些建議。

首先,我使用了很棒的在線課程來學習Java編程。 Tim Buchalka教授一門有關Java的非常深入的課程,該課程從一開始就開始,但逐步發展為高級主題。 您可以在這里找到他的Complete Java Masterclass

另外, BlueJ非常適合非常小的項目,但是如果您打算超越基礎知識,我建議您使用完整的Java IDE。 IntelliJ IDEA不僅免費,而且比EclipseNetbeans還成熟一些,但可以自由選擇最適合的方式。

發生這種情況是因為您嘗試訪問的字段不是該類的直接成員。 若要解決此問題,您需要在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;
}

之后,在方法中添加其余代碼。 確保將access modifier as public

現在,您可以在第二個類中使用Student對象設置屬性並調用方法。

  1. 理想情況下,StudentData2類應為模型類,並且所有邏輯都應進入處理類。

  2. 兩個主要方法表示兩條不同的路徑,在StudentData2中不需要主要方法。

  3. 要直接回答您的確切問題,“要修改另一個對象,您必須引用該對象”。 在這里您沒有它,因為您尚未在StudentData2上創建對象

您的程序應該看起來像這樣。

公共課程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 + "]";
}    

}

和演示類作為

導入java.util.Scanner;

公共課程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