[英]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 個問題。
6
。 理想情況下,您應該遷移到使用java.time
中定義的現代類,例如 LocalDate,它們的行為不會令人驚訝。int
沒有前導零。 但是您可以使用String.format
對其進行零填充。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.