簡體   English   中英

更改 static 變量的值

[英]Change the value of static variable

我想設置monthBtn的變量,並通過調用 function 來更改月份的變量。

private static String monthBtn;

    public static String getCurrentMonth() {
        int month = Calendar.getInstance().get(Calendar.MONTH);
        String monthBtn= "//*[@text='"+month+"']";
        System.out.println(yearBtn);
        return monthBtn;
    }
    public static void main(String[] args) {
        getCurrentMonth();
        System.out.println("Xpath Year ="+monthBtn);
    }

當我運行此代碼時,變量monthBtn的值返回 null 值,但我的預期條件是//*[@text='07']

我發現您的代碼存在 3 個問題。

  1. Calendar.get(MONTH) 返回的“月份”不是數字月份,而是 Calendar class 中定義的常量之一。 例如,對於 7 月份,它返回6 理想情況下,您應該遷移到使用java.time中定義的現代類,例如 LocalDate,它們的行為不會令人驚訝。
  2. 格式化。 int沒有前導零。 但是您可以使用String.format對其進行零填充。
  3. 可變的可見性。 您正在聲明一個本地monthBtn變量,該變量隱藏了同名的 static 變量。

您可以通過將方法中的代碼更改為:

    int month = LocalDate.now().getMonthValue();
    monthBtn = String.format("//*[@text='%02d']", month);
private static String monthBtn;

public static String getCurrentMonth() {
    int month = Calendar.getInstance().get(Calendar.MONTH);
    monthBtn= "//*[@text='"+month+"']"; //you should assign value to the class member, in your code you were declaring local variable.
    System.out.println(yearBtn);
    return monthBtn;
}
public static void main(String[] args) {
    String str = getCurrentMonth(); //you should store the value returned in some variable
    System.out.println("Xpath Year ="+str); //here you were referring to the class member `monthBtn` variable, which is null, and now you take the local str value.
}

我希望你現在明白為什么你會得到null 您有局部變量,並且getCurrentMonth()的返回值沒有存儲在任何地方。

更新您的代碼,如下所示。 您正在創建同名的局部變量,而不是為 static 變量賦值。 此外,如果您期望它 Calender.MONTH 將提供電流,則並非如此。 由於月份從 0 開始。所以如果當前月份是 7 月,您將得到 6 而不是 7

private static String monthBtn;

public static String getCurrentMonth() {
    int month = Calendar.getInstance().get(Calendar.MONTH);
    monthBtn= "//*[@text='"+month+"']";
    return monthBtn;
}
public static void main(String[] args) {
    getCurrentMonth();
    System.out.println("Xpath Year ="+monthBtn);
}

暫無
暫無

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

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