簡體   English   中英

從同一個 class 中的另一個私有方法訪問變量 - 這可能嗎?

[英]Accessing a variable from another private method within the same class - is this possible?

我得到指示創建一個返回 Int“inputAge”的方法,條件是來自方法“run”的先前輸入變量“age”大於 18。

但是,由於 Int“age”是在“run”方法中聲明和定義的,我無法在從“inputAge”返回 int 的方法中訪問它,因此我無法檢查 Int“age”是否大於 18。

指令 state 我必須在此代碼中使用“inputAge”方法,因此在“run”方法中不檢查輸入變量“age”是否大於 18。

這些說明是從我分配的工作表中逐字提取的(請原諒任何英語不好的老師):

"在代理示例中添加以下功能。年齡需要大於或等於 18。如果年齡小於 18,程序會再次詢問,直到輸入大於等於 18 的數字。你應該實現一個方法名為 inputAge 並從運行中調用該方法。方法如下(已添加在計算機實驗室可用的 Java 文件中)"

public int inputAge()
{
        // add the code here to receive an integer number as input and 
        // check if the number is greater or equal to 18
        // if the number is less than 18, the program should ask the number again
        // until the input number is greater or equal to 18
        return(0);//note that 0 was added here just to be able to compile
}
import java.util.*;

public class AgencyInterface 
{ 
    private void run() 
    {
       Scanner console = new Scanner(System.in);
       Couple c = new Couple();
       int      age,end;
       String   name;
       
       do {
           System.out.print("first person: "); 
           System.out.print("name: "); 
           name = console.next();
           System.out.print("age: "); 
           age = console.nextInt();
           c.addData(1,name,age);

           System.out.print("second person: "); 
           System.out.print("name: "); 
           name = console.next();
           System.out.print("age: "); 
           age = console.nextInt();
           c.addData(2,name,age);

           System.out.println("********************");
           System.out.println(c.test());           
           System.out.println("********************");
           System.out.print("Quit? (0)yes (1)no: "); 
           end = console.nextInt();
           }
       while (end!=0);
    }
    public static void main(String[] args)
    {
           AgencyInterface agency = new AgencyInterface ();
           agency.run();
    }
    public int inputAge()
    {
            // add the code here to receive an integer number as input and 
            // check if the number is greater or equal to 18
            // if the number is less than 18, the program should ask the number again
            // until the input number is greater or equal to 18

                // The four comments above give instruction again what to do within here.
                // They were not written by me (Lachshmock).
            return(0);//note that 0 was added here just to be able to compile

    }

    }

看起來您需要替換出現的兩個行:

System.out.print("age: "); 
age = console.nextInt();

age = inputAge();

然后inputAge應該是這樣的:

public int inputAge()
{
    int age;
    do {
        // Get the age from stdin. Print error if < 18
    } while (age < 18);
    return age;
}

我遺漏了一些東西,因為這看起來像家庭作業。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM