[英]Java Substring in if statement does not work
I'm trying to remove the last char in the string using substring
method.我正在尝试使用
substring
方法删除字符串中的最后一个字符。 Outside the if statement works normally.在 if 语句之外正常工作。 But inside it just goes through the if statement and returns original
String
.但在它内部只是通过 if 语句并返回原始
String
。
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
for (int i = 0; i < p; i++) {
vysledek += elkon[i];
vysledek += " ";
System.out.println(vysledek);
}
***if(zbytek != 0){
vysledek = vysledek.substring(0, vysledek.length() - 1);
return vysledek;
}
else{
return vysledek;
}***
}
Your code would be more straightforward if you didn't have to trim the trailing space from appending your String
(s).如果您不必通过附加
String
来修剪尾随空格,您的代码会更简单。 Also, it isn't clear why you expect zbytek
to control the trim
.此外,不清楚为什么您希望
zbytek
控制trim
。 I think you wanted if (p != 0)
(since that is your loop sentinel).我想你想要
if (p != 0)
(因为那是你的循环哨兵)。 I would use a StringJoiner
to implement this like我会使用
StringJoiner
来实现这个
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
StringJoiner sj = new StringJoiner(" ");
for (int i = 0; i < p; i++) {
sj.append(elkon[i]);
}
return sj.toString();
}
The last character in the string is a space, since you added it last time in the for
loop.字符串中的最后一个字符是一个空格,因为您上次在
for
循环中添加了它。
To trim the last space before if
statement you could use the code要修剪
if
语句之前的最后一个空格,您可以使用代码
public String getElkon(int p, int zbytek) {
System.out.println(zbytek);
for (int i = 0; i < p; i++) {
vysledek += elkon[i];
vysledek += " ";
System.out.println(vysledek);
}
if (p > 0)
vysledek = vysledek.substring(0, vysledek.length() - 1);
if(zbytek != 0){
...
}
return vysledek;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.