gpt4 book ai didi

java - StringBuilder.append(String str); 发生了一些疯狂的事情;

转载 作者:行者123 更新时间:2023-12-02 07:40:24 27 4
gpt4 key购买 nike

我的 java 项目有问题。

以下函数应该为 SQL 语句传递一个字符串:

private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();


x.append("" + p.getPatnr() +","+ p.getSvnr());

java.sql.Date andat = null,gebdat;

if(p.getAndat()==null)
andat=null;
else
andat=new java.sql.Date(p.getAndat().getTimeInMillis());

if(p.getGebdat()==null)
gebdat=null;
else
gebdat=new java.sql.Date(p.getGebdat().getTimeInMillis());

x.append("," + andat==null?"null":andat);
x.append("," + p.getTele()==null?"null":p.getTele());
x.append("," + p.getVName() +","+ p.getNname());
x.append("," + p.getKk()==null?"null":p.getKk());
x.append("," + gebdat==null?"null":gebdat);
x.append("," + p.getAdrplzort()==null?"null":6);
x.append("," + p.getAdrstr()==null?"null":p.getAdrstr());
x.append("," + p.getAdrhnr()==null?"null":p.getAdrhnr());
s.append("," + p.getReplzort()==null?"null":p.getReplzort().getPlzortnr());
x.append("," + p.getRestr()==null?"null":p.getRestr());
x.append("," + p.getRehnr()==null?"null":p.getRehnr());
x.append("," + p.getLevel());
x.append("," + p.getCon()==null?"null":p.getCon());
x.append("," + (p.isPa()?"y":"n")+","+ (p.isLonly()?"y":"n") +","+ (p.isGest()?"y":"n"));
x.append("," + p.getBem()==null?"null":p.getBem());
x.append("," + (p.isKat1()?'y':'n') +","+ (p.isKat2()?'y':'n') +","+ (p.isKat3()?'y':'n'));

System.out.println(x);

return x.toString();
}

输出为

6,6465136nullnull,Jürgen,Wieslernullnull6nullnullnullnull,0null,n,n,nnull,n,n,n

但它应该是这样的:

6,6465136,null,null,Jürgen,Wiesler,null,null,6,null,null,null,null,0,null,n,n,n,null,n,n,n

有人有想法吗?我在 debian(64 位)上使用 jdk 1.7

最佳答案

问题在于运算符如何绑定(bind)。看看这个:

x.append("," + andat==null?"null":andat);

现在将其视为:

x.append(("," + andat) == null ? "null" : andat);

LHS永远不会为空,所以它总是只是附加andat...并且仍然转换为“null”如果引用为 null,因为这是 StringBuilder 的默认行为。

您的代码比它需要的复杂得多,而且效率低下。考虑将其重写为:

private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();
java.sql.Date andat = p.andat == null ? null
: new java.sql.Date(p.getAndat().getTimeInMillis());
java.sql.Date gebdat = p.getGebdat() == null ? null
: new java.sql.Date(p.getGebdat().getTimeInMillis());

x.append(p.getPatnr()).append(",")
.append(p.getSvnr()).append(",")
.append(andat).append(",")
.append(p.getTele()).append(",")

// etc

return x.toString();
}

请注意,我认为您在原始版本中存在错误:

x.append("," + p.getVName() +","+ p.getNname());

这些意味着在哪里调用两个不同的 getter?

关于java - StringBuilder.append(String str); 发生了一些疯狂的事情;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10300387/

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