Java Beginner Recursion with boolean - java

I don't understand why I am getting "return statement missing".
Here is the image with the code:

In your 2nd and 3rd if conditions there are no returns. Instead of your else, just return false.
So it reads:
public class isTrans {
public static boolean isTrans(String s,String t) {
if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){
return true;
} else if (s.charAt(0)==t.charAt(0)){
return isTrans(s,t.substring(1));
} else if (s.charAt(1)==t.charAt(1)){
return isTrans(s,t.substring(1), t);
}
return false;
}
}

In this case you have to return in all the conditions or return at the end of the method.

if(/*...*/) {
return true;
}
else if(/*...*/) {
return isTrans(/*...*/); // return whatever isTrans returns
}
else if(/*...*/) {
return isTrans(/*...*/); // here too
}
else {
return false;
}

You have to return the result of the function execution in your else if, so the recursion works properly. Like this:
return isTrans(s, t.substring(1))

Related

Boolean use for decision making

Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean in the correct way.
public Space fire()
{
System.out.println("Hi");
}
public boolean hitRateAnalysis()
{
if (HitShipPercentage < 50 && Shots!=0)
return true;
else{
return false;
}
}
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.
This will call the fire method correctly:
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots != 0){
fire();
return true;
}
return false;
}
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space. I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.
public void fire() {
System.out.println("Hi");
}
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots!=0) {
fire();
return true;
}
return false;
}

Binary search tree String search

I have a program where I need to search for a specific word in a binary tree, the code I came up with for the search method for the string is not working. if someone could take a look at it I would greatly appreciate it.
I have tried a few alterations to this but it still did not work.
public boolean check(BSTNode t,String key){
if(!t.word.equals(key)){
check(t.left,key);
check(t.right,key);
}
else{
return true;
}
return false;
}
This could be written like this;
public boolean check(BSTNode t,String key) {
return
t.word.equals(key) || check(t.left,key) || check(t.right,key)
}
or, more verbosely;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
You don't need a lot of else statements because the return statements stop execution in the function.
Edit:
You must also check to see that your BSTNode is not null, or you will get null pointer exceptions when you reach the end of the tree. This could be done at the start of the function, or before the inner recursive check calls:
public boolean check(BSTNode t,String key) {
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
or;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (t.left != null && check(t.left,key)) return true;
if (t.right != null && check(t.right,key)) return true;
return false;
}

Is it possible the condition in IF ELSE statement is a method?

i was wondering if its possible for method to be the condition in if else statements.
i have a method called takephoto(). if takephoto() was successfully done it will do another method.
i did it this way
if (takephoto() == true)
{
anothermethod();
}
i get an error that says
The operator == is undefined for the argument type(s) void, boolean
for the line
if (takephoto() == true)
this is my takephoto()method
public static void takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
}
}
The method takephoto should return boolean, not void (i.e. nothing).
Then the answer is yes, but you should write it like this:
if (takephoto()) {
// do something
}
Your version will work too but this one is simpler and cleaner.
If takephoto() returns a boolean, that return value is itself the condition for your if statement, so you can write it as:
if (takephoto()) {
...
}
You'll have to make your takephoto() return a boolean, not a void value.
---- EDIT ----
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
else
return false;
}
if (takephoto()) {
}
public boolean takephoto()
{
return true; //or false
}
Yes, you can do this but your takephoto() method should return either true or false.
public static boolean takephoto(){
//if the code was successful
return true;
}
Or return false if picture was unsuccessful.
Here's how you could fix it:
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
else{
return false;
}
}
You say "if takephoto() was successfully done it will do another method." You have to have a way for takephoto to indicate if it was successful. The way you do that is to return a boolean.
yes, you can, but if statement checks between two parameters of same type.
your if statement:
if (takephoto())
{
///if takephoto() true
anothermethod();
}
your takephoto method:
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
return false;
}

Exception in thread "main" StackoverFlow error

I am writing a program that verifies if a password meets the appropriate requirements. I have all of my code written, and I feel it should work, but I get the following error:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.length(String.java:623)
at PasswordVerifier.isValid(PasswordVerifier.java:5)
at PasswordVerifier.isValid(PasswordVerifier.java:6)
and then it repeats the last line of the error for quite some time. I've been looking around and cannot seem to figure out my issue. I know something is continually looping that I don't want to, but the fix eludes me. Here is my code
public class PasswordVerifier{
private static int MIN_PASSWORD_LENGTH = 6;
public static boolean isValid(String str){
if (str.length() >= MIN_PASSWORD_LENGTH){
if (PasswordVerifier.isValid(str) == true){
if (PasswordVerifier.hasUpperCase(str) == true){
if (PasswordVerifier.hasLowerCase(str) == true){
if (PasswordVerifier.hasDigit(str) == true){
return true;
}
}
}
}
}
return false;
}
private static boolean hasUpperCase(String str){
for (char c : str.toCharArray()){
if (Character.isUpperCase(c)){
return true;
}
}
return false;
}
private static boolean hasLowerCase(String str){
for (char c : str.toCharArray()){
if (Character.isLowerCase(c)){
return true;
}
}
return false;
}
private static boolean hasDigit(String str){
for (char c : str.toCharArray()){
if (Character.isDigit(c)){
return true;
}
}
return false;
}
}
Any help would be appreciated!
public static boolean isValid(String str){
// ...
if (PasswordVerifier.isValid(str) == true){
// ...
}
// ...
}
You're calling isValid(String) from within itself, which is causing the infinite loop recursion.
I'm going to take a wild guess and say this is what you want instead:
public static boolean isValid(String str){
if (str.length() >= MIN_PASSWORD_LENGTH){
// Removed call to .isValid(String)
if (PasswordVerifier.hasUpperCase(str)){
if (PasswordVerifier.hasLowerCase(str)){
if (PasswordVerifier.hasDigit(str)){
return true;
}
}
}
}
return false;
}

How to return a boolean method in java?

I need help on how to return a boolean method in java. This is the sample code:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}
else {
addNewUser();
}
return //what?
}
I want the verifyPwd() to return a value on either true or false whenever I want to call that method. I want to call that method like this:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value for that method?
You're allowed to have more than one return statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true or false, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
System.out.println("password do not match");
}
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
Best way would be to declare Boolean variable within the code block and return it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.

Categories