这可能是一个noob问题,因为我刚刚开始使用Java。我用自己的类创建了一个Person对象,并创建了一个创建实际对象的主类(它也是一个数组)。但是,我现在正尝试在另一个类中访问此对象。如何将当前对象更改为能够在Main类之外使用?
Main.java
package me.chris.pizzacost;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat f = new DecimalFormat("##.00");
Scanner scan = new Scanner(System.in);
static Person[] people;
System.out.println("Welcome to Pizza Cost!\nTo start, how many people are in on this order?");
people = new Person[scan.nextInt()];
scan.nextLine();
System.out.println("Type their names, pressing ENTER between names.");
for (int x = 0; x<people.length; x++) {
//System.out.println("ran");
people[x] = new Person();
people[x].name = scan.nextLine();
//System.out.println("hit the end");
}
}
}
Person.java
package me.chris.pizzacost;
public class Person {
static String name = "blank";
static double cost;
}
答案 0 :(得分:1)
首先
static String name = "blank";
static double cost;
不应该是静态的:
package me.chris.pizzacost;
public class Person {
String name = "blank";
double cost;
}
创建一个主要类的setter:
public class Main {
//etc...
public static Person[] people; //put the declaration here. as a class member.
public static void setName(int element, String name){
people[element].name = name; //set the name of the specified element in the array.
}
在任何其他课程中,只需在STATIC CONTEXT中调用Main.setName(personID, "The Name");
或者只是让people
成为public static
班级成员,然后致电Main.people[element].name = "Whatever name"
(例如:)
package me.chris.pizzacost;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static Person[] people; //put the declaration here. as a class member.
public static void main(String[] args) {
DecimalFormat f = new DecimalFormat("##.00");
Scanner scan = new Scanner(System.in);
// static Person[] people; (get rid of this)
System.out.println("Welcome to Pizza Cost!\nTo start, how many people are in on this order?");
people = new Person[scan.nextInt()];
scan.nextLine();
System.out.println("Type their names, pressing ENTER between names.");
for (int x = 0; x<people.length; x++) {
//System.out.println("ran");
people[x] = new Person();
people[x].name = scan.nextLine();
//System.out.println("hit the end");
}
}
}