Home > Back-end >  Pulling Methods via If statements [duplicate]
Pulling Methods via If statements [duplicate]

Time:10-05

In this block, I am trying to execute a method if a variable equals a specific value. I am not sure why this block is not executing. How do I fix this? Why is it not executing?

package lab3project; import java.util.Scanner;

public class LabNS3 {
    public static int addNumbers(int x, int y) {
        return x y;
    }
    
    public static void main(String[] args) {
        
        Scanner input1 = new Scanner(System.in);
        System.out.print("Type first number: ");
        int num1 = input1.nextInt();
        
        Scanner input2 = new Scanner(System.in);
        System.out.print("Type a character: ");
        String sign1 = input2.nextLine();
        
        Scanner input3 = new Scanner(System.in);
        System.out.print("Type second number: ");
        int num2 = input3.nextInt();
    
        if(sign1 == " ") {
        int sum = addNumbers(num1, num2);
        System.out.print(sum);}

        }
    }

CodePudding user response:

if(sign1 == " ") {

should be

if(sign1.equals(" ")) {

CodePudding user response:

In java, a string is not a primitive type(char, int ,double), so in your case you can either cast your input to a character or use the built in .equals(). eg. sign1.equals(" ")

CodePudding user response:

Don't compare Strings with ==, but equals() instead as follows:

if(" ".equals(sign1)) {
  int sum = addNumbers(num1, num2);
  System.out.print(sum);}
}

We can use == operators for reference comparison (address comparison) and equals() method for content comparison. This means that you are comparing object references instead of String content. It is noteworthy that Strings are usually optimized (by storing only one copy of each String in the Java String Pool) so that two Strings with the same value can actually be compared with == and return true (because they actually pointing to the same reference), but it's better not to rely on that and always use equals().

  •  Tags:  
  • java
  • Related