Solocid
Solocid

Reputation: 53

Finding smallest String / Word

I am new to Java and programming in general, keep that in mind and don't be harsh on me please ^^. Next on I did some training with Java recently and I love the challenge however right now I am just stuck. I did some examples to find the largest string typed from the user and it all went fine, however now I just wanted the opposite to find the smallest one, and it just won't show it as output, it only shows blank as the result. Here's the code:

/* Gjen fjalen me te vogel te shtypur nga user-i dhe e paraqet si rezultat se bashku me numrin total te fjaleve te shtypura */

import java.util.*;
public class fjalaMin {
    private static Scanner sc;
    public static void main(String[]args) {
        sc = new Scanner(System.in);
        String fjalet ="";
        String fjalaMin ="";
        String SENTINEL ="FUND";
        int count = 0;

        System.out.println("Shtypni fjalet e deshiruara ose shtypni ' FUND ' per te terminuar programin: ");
        do {
            fjalet = sc.nextLine();
            if(fjalet.equalsIgnoreCase(SENTINEL)) {
                break;
            } else if(fjalet.length() < fjalaMin.length()) {
                fjalaMin = fjalet;
            }

            count++;
        }
        while(!fjalet.equalsIgnoreCase(SENTINEL));

        if(count == 0) {
            System.out.println("Nuk keni shtypur asnje fjale!");
        } else {
            System.out.println("Rezultati juaj: ");
            System.out.println("Numri total i fjaleve te shtypura: " + count);
            System.out.println("Fjala me e shkurte qe eshte shtypur eshte: " + fjalaMin);
        }
    }
}

Upvotes: 0

Views: 133

Answers (1)

kai
kai

Reputation: 6887

The problem is that you initialize String fjalaMin = ""; with an empty String, so no string is shorter. You can initialize it with a long String or if you want to be safe you can initialize it with null and change your condition to:

else if (fjalaMin == null || fjalet.length() < fjalaMin.length())
{
    fjalaMin = fjalet; // always the first input will be stored
}

Now it should work fine.

Upvotes: 2

Related Questions