首页 > 解决方案 > 我需要将变量传递给方法

问题描述

在我的代码中,我创建了一个名为 Points 的类,它检查给定问题的答案并返回分数。另一个名为 Report 的类需要一些信息来打印它

package finalproject;

public class Points {

public static float calculatePoints(byte[] userAnswer) {

    byte realAnswer[], gradeCounter;
    float score ;
    gradeCounter = 0;

    realAnswer = new byte[3];
    realAnswer[0] = 3;
    realAnswer[1] = realAnswer[2] = 1;

    for (int i = 0; i < userAnswer.length; i++) {
        if (userAnswer[i] == realAnswer[i]) {
            gradeCounter++;
        }
    }

    score = (gradeCounter / 3) * 100;

    return score;
}



}

package finalproject;

public class Report {

public static void getLoginInfo(String[] loginInformation) {

    loginInformation = new String[2];
    String name, id;
    name = loginInformation[0];
    id = loginInformation[1];

}

public static void printReport() {

    System.out.println("\n\n-------------------\n\n");
    System.out.println("\t\tJava Certification");
    System.out.println("\t\t Test Result\n\n");
    System.out.println("\tName: ");
    System.out.println("\tTest Registration ID: ");
    System.out.println("\tPassing Score 52%");
    System.out.println("\tYour Score: ");

    /*
     * if (score1 >= 52.0) { System.out.println("\n\nComment GRADE: pass\n\n"); }
     * else { System.out.println("\n\nComment GRADE: fail\n\n"); }
     */

    System.out.println("Max Score\t" + "---------------100%");
    System.out.println("Max Score\t" + "--------52%");

}

}

在名为 name 和 id 的 getLoginInfo 变量中应该设置,我想将它们传递给 printReport。

我想将函数 calculatePoint() 中名为 score 的变量传递给 printReport 我该怎么做?

标签: javamethodsstatic

解决方案


如果您在任何函数之外声明 name 和 id,则字符串 name 和 id 的范围将是类的范围,这意味着它将对类 Report 中的所有函数可见。类报告的每个对象/实例都将具有名称和 ID 作为属性。然后getLoginInfo可以用来设置,printReport()可以用来打印name和id。

public class Report {
String name, id;
public static void getLoginInfo(String[] loginInformation){
    name = loginInformation[0];
    id = loginInformation[1];

}

public static void printReport() {

  ...
}
}



推荐阅读