2017-09-05 194 views
1

我很新的Java和搜查通過以前問這並沒有幫助我的問題的問題...如何在類之間傳遞變量?

我如何通過int變量年齡和字符串名稱,從主類的人類?

package engineers; 

import java.util.Scanner; 


public class Engineers { 

    public static void main(String[] args) { 
     // TODO code application logic here 

     Scanner scan = new Scanner(System.in); //declaration and ssignment of scanner 
     System.out.println("Enter name: "); //name prompt 
     String name = scan.next(); //reads name input from user 

     System.out.println("Enter age: "); //age prompt 
     int age = scan.nextInt(); //reads age input from user 

     System.out.println("Pay check amount: "); 
     double salary = scan.nextDouble(); 
     Person person = new Person(); 


    } 

    private static class Person { 
     /** 
     * A default constructor 
     */ 
     public Person() { 
     } 
     /** 
     * method for displaying the computation result 
     */ 

     double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * age + 0.141)); 


     public void showData(int age, double pay){ 
      System.out.printf("%s earns $%4.3f for age %3d.\n", name, (pay*Math.sqrt(age)*.15), age); 
     }//end method showData 
    } 

} 
+0

您通過年齡以同樣的方式,你傳遞'String'到'println'或浮點值'Math.exp'你的代碼是充滿了如何做到這一點的例子。 –

回答

2

您應該使用人的構造是這樣的:

public Person(int age, String name) { 
    this.age = age; 
    this.name = name; 
} 

而在你的Person類添加兩個字段,你的構造函數之前:

private int age; 
private String name; 

然後我假設你需要使用Person類裏面這個變量,爲了做到這一點,你可以做這樣的事情:

double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * this.age + 0.141)); 

要引用您的變量:

public void showData(){ 
    System.out.printf("%s earns $%4.3f for age %3d.\n", this.name, (pay*Math.sqrt(this.age)*.15), this.age); 
}//end method showData 

Finnaly,你需要實例化Person對象使用它:

Person p = new Person(name, age); 

我也建議(因爲你是學習java),瞭解getter/setter方法和構造方法之間的區別:Setter methods or constructors

+1

是的,你是對的! @PeterLawrey謝謝! –

0

你的意思是這樣的嗎?

int age; 
String name; 

class Person(int age, String name) { 
     this.age = age; 
     this.name = name; 
} 

或(和)

void setAge(int age) { 
    this.age = age; 
} 

void setName(String name) { 
    this.name = name; 
} 
0

你會想要定義的任何說法另一個類可能需要最基本的功能構造。 一個Person istance將與一個名字和年齡(即使它會更好地存儲出生日期和計算年齡的針對當前日期)來初始化。

要做到這一點,你需要的類Person看起來像這樣:

public class Person{ 
    private String name; 
    private Date birthdate; 

    //Constructor method 
    public Person(String n, Date bd){ 
     name=n; 
     birthdate=bd; 
    } 
    //Other methods 
} 

main()方法,你會然後創建Person新istance,越來越需要什麼,這樣以後:

Person p = new(name, date);