Java 不确定我做错了什么,简单的中间子串
下面是我正在做的简单练习的链接:Java 不确定我做错了什么,简单的中间子串,java,string,Java,String,下面是我正在做的简单练习的链接: 然而,它告诉我当它使front=false时 public String theEnd(String str, boolean front) { String stringPart; if (front = true) { stringPart = str.substring(0, 1); } else { s
然而,它告诉我当它使front=false时
public String theEnd(String str, boolean front) {
String stringPart;
if (front = true) {
stringPart = str.substring(0, 1);
} else {
stringPart = str.substring(str.length()-1,str.length());
}
return stringPart;
}
不管怎样,返回为true时的值。我不想学坏习惯:(
例如:大象返回E,当它应该返回t时。我稍后会回来检查,我需要休息一下。可能会犯愚蠢的错误这就是问题所在:
if (front = true)
你的意思是:
if (front == true)
目前,它正在为front
分配一个新的true
值,然后计算结果并发现它是真的-因此它将始终使用第一个字符
有三种方法可以解决这个问题。一种方法如上所述,只是要更加小心。一种是使用:
if (true == front)
这将阻止您输入错误,因为您无法将常量赋值为true
然而,我更愿意完全摆脱文字:
if (front)
但是,也可以使用条件运算符简化整个方法:
public String theEnd(String str, boolean front) {
int start = front ? 0 : str.length() - 1;
return str.substring(start, start + 1);
}
这就是问题所在:
if (front = true)
你的意思是:
if (front == true)
目前,它正在为front
分配一个新的true
值,然后计算结果并发现它是真的-因此它将始终使用第一个字符
有三种方法可以解决这个问题。一种方法如上所述,只是要更加小心。一种是使用:
if (true == front)
这将阻止您输入错误,因为您无法将常量赋值为true
然而,我更愿意完全摆脱文字:
if (front)
但是,也可以使用条件运算符简化整个方法:
public String theEnd(String str, boolean front) {
int start = front ? 0 : str.length() - 1;
return str.substring(start, start + 1);
}
您需要检查与的相等性
if (front == true)
您需要检查与的相等性
if (front == true)
您在if语句中写入了(front=true)。这不会将front与true进行比较。这会将front设置为true
我很震惊你的编译器没有因为这句话对你大喊大叫。你应该得到一个警告。如果可以,请确保你在编译时打开了所有警告选项,然后注意每个警告。你写的(front=true)在if语句中。这不会将front与true进行比较。这会将front设置为true
我很震惊你的编译器没有因为这句话对你大喊大叫。你应该得到一个警告。如果可以,请确保你在编译时打开了所有警告选项,然后注意每个警告。Graah!!!我现在觉得自己像个白痴:(我已经学了一千次了,而且总是至少犯一次错误:DGraah!!!我现在觉得自己像个白痴