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;
}
가장 먼저
static String name = "blank";
static double cost;
정적이면 안됩니다.
package me.chris.pizzacost;
public class Person {
String name = "blank";
double cost;
}
세터도 메인 클래스로 만듭니다.
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.
}
다른 클래스 Main.setName(personID, "The Name");
에서는 In STATIC CONTEXT를 호출하십시오 .
아니면 그냥 클래스 멤버를 만들고 그냥 전화 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");
}
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다