Search code examples
javastringcomparestring-comparison

how to Compare the second part of the text in java?


It is necessary to compare the second half of the text to see if they are brothers or not

I tried to find a solution to this problem

This is the problem link

https://codeforces.com/group/MWSDmqGsZm/contest/219158/problem/L

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String s1 = in.next();
    String s2 = in.next();
    String s3 = in.next();
    String s4 = in.next();

    if (s3.length() == s4.length()) {
        System.out.println("ARE Brothers");
    } else {
        System.out.println("NOT");
    }
}

}


Solution

  • Get the inputs, split by a space and get the second item in the resulting array to get the last name. Then compare the two using a ternary operator.

    Scanner s = new Scanner(System.in);
    String firstLastName = s.nextLine().split(" ")[1];
    String secondLastName = s.nextLine().split(" ")[1];
    String result = firstLastName.equals(secondLastName) ? "ARE Brothers" : "NOT";
    System.out.println(result);