Click here to Skip to main content
15,893,508 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int result line is most confusing

What I have tried:

Java
import java.util.stream.IntStream;

public class Palindrome {
    public static void main(String[] args) {
        String num = "1234321";
        int pos = num.length()-1;
        int middle = num.length()/2;
        int result = IntStream.rangeClosed(0, middle).anyMatch(i -> num.charAt(i) != num.charAt(pos - i)) ? 0 : 1;
        System.out.println(result!=1?"false":"true");



        }
Posted
Updated 15-Jun-22 0:31am
v2

it's just calling a method called rangeClosed, then using the result of that to call a method called anyMatch with returns true if the condition evaluates to true on one or more of the items in the collection.
That true or false result is used to select 0 if it's true, and 1 if it's false

Break it down into separate lines which store the result and it's more obviuous to beginners:
Java
int result;
var range = IntStream.rangeClosed(0, middle);
var foundAMatch = range.anyMatch(i -> num.charAt(i) != num.charAt(pos - i));
if (foundAMatch) {
   result =  0;
   }
else {
   result = 1;
   }
 
Share this answer
 
Comments
CPallini 15-Jun-22 6:19am    
5.
Note, the posted code is equivalent to the more expicit (and possibly cleaner))
Java
public static void main(String[] args)
{
  String num = "12344321";
  int last = num.length()-1;
  int middle = last/2;

  int i;
  for ( i = 0; i < middle; ++i)
  {
    if (num.charAt(i) != num.charAt(last-i))
    {
      break;
    }
  }
  System.out.printf("%b\n", (i == middle));
}
 
Share this answer
 
Comments
Patrice T 15-Jun-22 7:24am    
+5
CPallini 15-Jun-22 7:28am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900