gpt4 book ai didi

java - 更新具有相同名称的变量值

转载 作者:行者123 更新时间:2023-12-02 04:24:44 25 4
gpt4 key购买 nike

有人可以告诉我以下内容是否正确吗?

我想在私有(private)方法 isThisValid() 中使用相同的变量来执行两个不同的任务。下面的内容会根据我的需要更新这些值吗?

public boolean validateDate(String dateForValidation, String format) {
this.dateFormat = format;
this.dateToValidate = dateForValidation;
isThisValid();
if(isThisValid() == true)
{
return true;
}
else{
throw new IllegalArgumentException(
dateToValidate + "did not match expected" + dateFormat);
}
}
public boolean validateTime(String TimeToValidate, String TimeFormat){
this.dateFormat = TimeFormat;
this.dateToValidate = TimeToValidate;
isThisValid();
if(isThisValid() == true)
{
return true;
}
else{
throw new IllegalArgumentException(
dateToValidate + "did not match expected" + dateFormat);
}
}

private boolean isThisValid(){
if (dateToValidate == null) {
logger.info(dateToValidate + "was equal to null");
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setLenient(false);

try {
// if not valid, it will throw ParseException
Date date = sdf.parse(dateToValidate);
System.out.println(date);

} catch (ParseException e) {
logger.info(dateToValidate + "did not match expected" + dateFormat + "throw ParseException");
logger.trace(
dateToValidate + "did not match expected" + dateFormat + "so it was not valid, so throw ParseException");
e.printStackTrace();
return false;
}

return true;
}

这行得通吗?

最佳答案

Will this work?

也许,在某些情况下。这实际上取决于您想要做什么,这在您的问题中并不清楚。

如果它被多个线程调用,它会做非常奇怪且不可预测的事情。

您通常不希望使用这样的可变状态:相反,请将 isValid 中所需的内容传递到 isValid 中:

public boolean validateTime(String timeForValidation, String format) {
if(isThisValid(timeForValidation, format) == true) {
return true;
}
throw new IllegalArgumentException(...);
}

public boolean validateDate(String dateForValidation, String format) {
if(isThisValid(dateForValidation, format) == true) {
return true;
}
throw new IllegalArgumentException(...);
}

private boolean isThisValid(String timeToFormat, String timeFormat){
// ...
}

它在多线程环境中不起作用的原因是 validateTime(或 validateDate)的一次调用不一定在下一次调用之前完成发生。下一次调用将使用 this.dateFormatthis.dateToValidate 的值,这意味着已经进行的调用将(可能)开始使用来自第二次调用,导致不可预测的结果。

关于java - 更新具有相同名称的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com