Home > front end >  How to assign the variable to a value in a conditional if statement
How to assign the variable to a value in a conditional if statement

Time:10-11

public String simpleConditional(int price)  {
        String answer = null ;
price = 20;
          if (price < 20)
              System.out.println("Buying new shirt");

How do I assign "Buying new shirt" to the answer variable? (Rookie question, this is also a homework checker in Vocareum)

CodePudding user response:

It is clear from the code snippet that the return type is "String" so what you can do is the following if you want to return "Buying new shirt".

public String simpleConditional(int price) {
   String answer = null;
   price = 20;
   if(price < 20) {
     System.out.println("Buy new shirt");
     answer = "buy new shirt";
     return answer;       
   } else {
     return "Something else"; 
   }
}

CodePudding user response:

It could be something like this:

/**
 * Assumes the monetary value supplied is a floating point value.
 * 
 * @param price (double) 
 * 
 * @return (String)
 */
public static String simpleConditional(double price) {
    String answer = null;
    if (price > 0d && price < 20d) {
        System.out.println("Buy new shirt");
        answer = "buy new shirt";

    }
    else if (price >= 20d && price < 80d) {
        answer = "Hmmm...buying a decent shirt!";
    }
    else if (price >= 80d) {
        answer = "Wow...Big Spender, buying a really good shirt!";
    }
    else {
        answer = "What? Changed your mind?";
    }
    return answer;
}

To use the method named simpleConditional() method within the class main() method you might do something like:

public static void main(String args[]) {
    String anAnswer = simpleConditional(56.98);
    System.out.println(anAnswer);

    // The following will work to:
    System.out.println(simpleConditional(104));
}
  • Related