将相同的值传递给方法并使其第一次 return 为真,第二次为假
Passing same value to a method and make it return true the first time and false the second time
是否可以将值传递给方法并声明它是唯一的?因此,我们第一次传递值 returns true 并保留该值,下一次传递 returns false 时,它会检查它是否已传递一次。有没有代码可以让它工作?
public class Main {
public static void main(String[] args){
Main bb = new Main();
String a1 = 3000;
String a2 = 3000;
boolean output3 = bb.addAccount(a1);
assertEquals(true, output3);
boolean output4 = bb.addAccount(a2);
assertEquals(false, output4);
}
public boolean addAccount(String acc) {
int store = 0;
boolean out = false;
if (acc == 3000 && store = 0){
out = true;
store = 1;
}
else if (acc == 300 && store != 0){
out = false;
}
return out;
}
}
// a class field
Set<String> seen = new HashSet<>();
// a set will return false when adding an existing value
// and return true otherwise. Since sets will not contain
// duplicates adding will not add additional values.
public boolean addAccount(String acc) {
return seen.add(acc);
}
如果这就是您想要做的全部,那么您不需要任何方法。如果方法中有更多处理,那么仍然使用集合,进行处理,并 return 适当的布尔值。
是否可以将值传递给方法并声明它是唯一的?因此,我们第一次传递值 returns true 并保留该值,下一次传递 returns false 时,它会检查它是否已传递一次。有没有代码可以让它工作?
public class Main {
public static void main(String[] args){
Main bb = new Main();
String a1 = 3000;
String a2 = 3000;
boolean output3 = bb.addAccount(a1);
assertEquals(true, output3);
boolean output4 = bb.addAccount(a2);
assertEquals(false, output4);
}
public boolean addAccount(String acc) {
int store = 0;
boolean out = false;
if (acc == 3000 && store = 0){
out = true;
store = 1;
}
else if (acc == 300 && store != 0){
out = false;
}
return out;
}
}
// a class field
Set<String> seen = new HashSet<>();
// a set will return false when adding an existing value
// and return true otherwise. Since sets will not contain
// duplicates adding will not add additional values.
public boolean addAccount(String acc) {
return seen.add(acc);
}
如果这就是您想要做的全部,那么您不需要任何方法。如果方法中有更多处理,那么仍然使用集合,进行处理,并 return 适当的布尔值。