Home > Blockchain >  Can't check if the last 3 letters of an array are the same in java
Can't check if the last 3 letters of an array are the same in java

Time:10-09

I have to check if the last 3 numbers of a number with 3 or more digits are the same. I have converted the number to a string called nombre. My code is this:

for(int i=nombre.length()-1;(i<nombre.length() && i>=0);i--){
        if(nombre.charAt(i)==nombre.charAt(i-1)){
            res  ;}
        }
        if(res==3){
            System.out.println("Les 3 derniers chiffres sont tous différents");
            
            }
        else if(res==2){
            System.out.println("Seuls deux des 3 derniers chiffres sont identiques");
            
            
            }
        else{
            System.out.println("Les 3 derniers chiffres sont tous différents");
            }

At the end I have to show if all the 3 digits are the same,or only the 2 digits ,or none of them.But I get an error that says: String index out of range: -1 .I don't understand why because I already made a condition for i to be greater than 0.

CodePudding user response:

Change nombre.charAt(i-1) to nombre.charAt(0) to avoid that error and make that work.

for(int i=nombre.length()-1;(i<nombre.length() && i>=0);i--){
    if(nombre.charAt(i)==nombre.charAt(0)){
       res  ;
    }
}

CodePudding user response:

Rather than get tangled up with indexes, you could use regex:

boolean last3Same = nombre.matches(".*(.)\\1\\1");

This also handles returning false if there are less than 3 characters in the string.

CodePudding user response:

Code point

The char type is essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, the char type is physically incapable of representing most of the over 140,000 characters defined in Unicode.

Use code point integer numbers when working with individual characters.

String input = String.valueOf( 789 );             // Convert an `int` primitive to text.
int[] codePoints = input.codePoints().toArray();  // Generate a stream of `int` primitives, each the code point for a character in our string. Collect those code points into an array.

Stream

With the help of streams, we can do all the business logic is a one-liner.

Pull the last 3 code points, box them to make Integer objects from int primitives, and call Stream#distinct to eliminate duplicates. Get count of remaining digits.

long size =
        Arrays
                .stream( codePoints )  // Make a stream of each code point in the array.
                .boxed()               // Convert from `int` primitive to `Integer` object.
                .toList()              // Make a `List` of those `Integer` objects.
                .subList( codePoints.length - 3 , codePoints.length )  // Focus on the last 3 digits’ code points only.
                .stream()              // Make a stream of those last 3 digits’ code points.
                .distinct()            // Eliminate duplicate code points.
                .count();              // Count remaining code points, and therefore a count of distinct digits in original number.

Use switch expression to create a message for the result of our count of duplicate digits.

String message =
        switch ( ( int ) size ) // Lossy cast needed, as oddly enough, in Java a switch cannot work on a `long` primitive.
                {
                    case 3 -> "No dups.";
                    case 2 -> "Two digits the same.";
                    case 1 -> "All three digits the same.";
                    default -> "ERROR - Unexpected switch case.";
                };
System.out.println( message );
  • Related