Sorting randomly genareted string in alphapetic order

import java.util.*;
public class test {
    public static char[] chars;
    public static Random random;
    static {
        chars = new char[26];//taking caracters from asci table
        for (int i = 0; i < 26; i ++) {
            chars[i] = (char) (97 + i);           
        random = new Random ();
    public static void main (String[] args) { //printing random characters
            for (int i = 1; i <= 10; i++ ) {                                                                          
            System.out.println(randomString(20)); 
    private static String randomString (int length) { //generating random
        char[] array = new char[length];
        for (int i = 0; i < length; i ++) {
            array[i] = chars[random.nextInt (chars.length)];
    return new String (array);
    i have this code.i found that in the forums and modified it a bit.but i have still problems to sort randomly genareted strings in alphabetic order.i have a method to do it.but i couldn't implement it correctly.the way that i try to sort them is
void sort(String[] a) {
  for (int i=0; i<a.length-1; i++) {
     for (int j=i+1; j<a.length; j++) {
        if (a.compareTo(a[j]) > 0) {
String temp=a[j];
a[j]=a[i];
a[i]=temp;
thats a method i try to use but i couldn't put it in a correct place in the code and couldn't call him.always it gives error.pls help this unexprienced java user...

Hard to understand your problems, because you're too vague. At one point you mention you don't know where to put your method, at another you say you don't know how to call your method. If that is the case (which seems unlikely but oh well) here's an example.
public class Testing9 {
     public Testing9() { // constructor
          String basicString = "BasicExample";
          String sortedString = mySortMethod(basicString); // call mySortMethod passing the string
          System.out.println("sortedString = " + sortedString);
     public static void main(String[] args) { // main method starts app
          Testing9 app = new Testing9(); // calls constructor
     public String mySortMethod(String s) { // put the method here cause I feel like it
          String sortedString = "";
          // do your own work here to sort, etc....
          return sortedString;
}

Similar Messages

  • [C] Trying to sort string into reverse order ... Blank. [SOLVED]

    Here are the pre-processors:
    #include <stdio.h>
    #include <string.h>
    Here are the global variables:
    char output[999];
    Here's the function to sort string to reverse order (I THINK THE PROBLEM IS HERE):
    char output[999];
    char *sort_reverse(const char *str)
    int i, j = 0;
    for (i = strlen(str); i > 0; i--)
    output[j] = str[i];
    j++;
    return output;
    And, function int main(void):
    int main(void)
    printf("Reverse of \"Hello\": %s\n", sort_reverse("Hello"));
    return 0;
    The output is:
    Reverse of "Hello":
    Why is that? how can i fix that?
    Last edited by milo64 (2013-03-28 01:45:46)

    Instead of the global char output[999] wich is really big, you could allocate a perfectly sized array with calloc - like this in the sort_reverse function:
    char *output = calloc(strlen(input_string), sizeof(char));
    and in main program:
    char *reversed_string = sort_reverse("Whatever");
    printf("%s\n", reversed_string);
    //Remember to free reversed_string with
    free(reversed_string);
    //Since its allocated in the heap with calloc()
    Try check man-page for calloc, it will zero out the bytes aswell, then you wont have to worry about setting the last element to '\0'.
    NOTE: you have to iterate with "strlen(input_string) - 1" otherwise you will overwrite the needed '\0'
    EDIT:  As strlen excludes the '\0' in original string, then you have to make space for that by adding one to strlen return value so:
    char *output = calloc(strlen(input_string) + 1, sizeof(char));
    Last edited by Boogie (2013-04-05 09:46:12)

  • How to sort  the arry value in ascending order

    I have a string array where i need to sort the below values in ascending order in the same format...can anyone give me clue on this?
    9.3
    3.1
    9.1
    19.1
    19
    9.4
    9.1.1
    the sorted order should be
    3.1
    9.1
    9.1.1
    9.3
    9.4
    19
    19.1

    You may have easier luck writing your own comparator for this. These are headings in a table of contents, right?
    Write a comparator that tokenizes a string on the '.' character, or use a StringBuffer to remove them, and then order the elements according to the combined numbers. Since alphanumeric would order this list as you want it anyway you could just order that way once the '.' are removed.
    In other words your comparator would do this in the "compare" method:
    public class MyComparator implements Comparator, java.io.Serializable {
    private static Comparator stringComparator = java.text.Collator.getInstance();
    ...constructor(s), your own private "instance" variable of type MyComparator, a getInstance() method of your own, yadda yadda...
    public int compare(Object item1, Object item2) {
    try {
    value1 = removePeriods((String)item1);
    value2 = removePeriods((String)item2);
    if (value1 == null) {
    return (value2 == null) ? 0 : (-1);
    return compare(value1, value2);
    } catch (ClassCastException cce) {
    System.err.println("Wrong Object Type, JackAss!");
    protected int compare(String str1, String str2) {
    return MyComparator.stringComparator.compare(str1, str2);
    private String removePeriods(String value) {
    StringBuffer sb = new StringBuffer(value);
    int decimalIndex = value.indexOf('.');
    while (decimalIndex != -1) {
    sb.delete(decimalIndex, (decimalIndex + 1));
    }

  • Sorting and Searching String (Please help me)

    Hi, Could somn please be of any help here. I am trying to sort this string in alphabetical order and then search for data available but I am not makingprogress with the code. Does anyone have any advise or better still the code to solve this problem... This is hat I have at the moment
    import java.util.*;
    import java.io.PrintStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    public class coursework2
         public static final int MAX_RECORDS = 20;
         public static String lastName[] = new String[MAX_RECORDS];
         public static String firstName[] = new String[MAX_RECORDS];
         public static String telNumber[] = new String[MAX_RECORDS];
         public static String emailAddress[] = new String[MAX_RECORDS];
         public static int read_in_file(String file_name)
              Scanner read_in;
              Scanner line;
              int record_count = 0;
              String record;
              try
                   read_in = new Scanner(new File(file_name));
                   // read in one line at a time
                   read_in.useDelimiter(System.getProperty("line.separator"));
                   while (read_in.hasNext())
                        // Test to see if there are too many records in the file
                        if (record_count == MAX_RECORDS)
                             System.out.printf("Only %d records allowed in file", MAX_RECORDS);
                             System.exit(0);
                        // read in record
                        record = new String(read_in.next());
                        // Split the record up into its fields and store in
                        // appropriate arrays
                        line = new Scanner(record);
                        line.useDelimiter("\\s*,,\\s*");
                        lastName[record_count] = line.next();
                        firstName[record_count] = line.next();
                        telNumber[record_count] = line.next();
                        emailAddress[record_count] = line.next();
                        // Increment record count
                        record_count++;
              catch (FileNotFoundException e)
                   e.printStackTrace();
              return record_count;
         public static void write_out_file(int no_of_records, String filename)
              PrintStream write_out;
              int counter;
              try
                   // Create new file
                   write_out = new PrintStream(new File(filename));
                   // Output all reacords
                   for(counter = 0; counter < no_of_records; counter++)
                        // Output a record
                        write_out.print(lastName[counter]);
                        write_out.print(",,");
                        write_out.print(firstName[counter]);
                        write_out.print(",,");
                        write_out.print(telNumber[counter]);
                        write_out.print(",,");
                        write_out.println(emailAddress[counter]);
                   // Close file
                   write_out.close();
              catch (FileNotFoundException e)
                   e.printStackTrace();
         // Your 'functions' go here
         //This code sorts out the record after loaded into alphabetical order using
         //the selection sort method
         public static void sort()
         // Your 'main' code goes here
         //The code below uses a binary search method to search for record because
         //record have been sorted and this would make search faster and more efficient
         public static boolean linearSearch(String strFirstName, String strLastName)
              //Set-up data_input and declare variables
              //This linear search searches for record in the contact application.
              //Search for a record using surname only
                   int i = 0;
                   boolean found = false;
                   while (!found && i < lastName.length)
                        if(strFirstName.equals("") && strLastName.equals(""))
                             return true;
                        if(lastName.equalsIgnoreCase(strLastName)){
                   //List records from surname only
                   System.out.println("Enter your search criteria (last name only):");
                        System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                        System.out.println("");
                        if (lastName[i].compareTo(strLastName) == 0)
                             //Compare the last name values and type to make sure they are same.
                             found = true;
                                  i++;
                                  System.out.print(lastName[i] +     "\t" + firstName[i] + "\t" + telNumber[i] +"\t" + emailAddress[i]);
                                       System.out.println("");
                             return found;
              //Search for a record using first name only
         public static void main(String[] args)
              // Set-up data input
              Scanner data_input = new Scanner(System.in);
              // Declare Variables
              int number_of_records;
              String filename;
              int counter;
              // Get filename and read in file
              System.out.print("Enter the masterfile file name: ");
              filename = data_input.next();
              number_of_records = read_in_file("data2.dat");
              //Get new filename and write out the file
              System.out.print("Enter new masterfile file name: ");
              filename = data_input.next();
              //System.out.println("Enter your search criteria (first or last name):");
              linearSearch("*", "");
    Am very sorry this is long, the file should be sorted after it is loaded and I have that, You can make up some data with last ane, first name, tel and email to show me an example. Thanks alot
    Joseph

    Hi Monica, Thanks for you patience with me.
    I have tried writing a selection sort method but am having some errors. Could you kindly have a lookand correct me please.
    This is the code i wrote
    public static void selectionSort(Comparable [] data)
              String strFirstName;
              String strLastName;
              Comparable temp;
              for(int i = 0; i < lastName.length; i++)
                   lastName = index;
                   for (int j = i; j < lastName.length; j++)
                        if (lastName[j].compareTo(lastName) < 0)
                             lastName[j] = lastName[i];
                   //Swap the string values
                   temp = lastName[j];
                   lastName[j] = lastName[i];
                   lastName[i] = temp;
    As you requested, below are 4 error messages I had
    E:\coursework2.java:101: cannot find symbol
    symbol : variable index
    location: class coursework2
                   lastName = index;
    ^
    E:\coursework2.java:107: cannot find symbol
    symbol : variable j
    location: class coursework2
                   temp = lastName[j];
    ^
    E:\coursework2.java:108: cannot find symbol
    symbol : variable j
    location: class coursework2
                   lastName[j] = lastName[i];
    ^
    E:\coursework2.java:109: incompatible types
    found : java.lang.Comparable
    required: java.lang.String
                   lastName[i] = temp;
    ^
    4 errors
    JCompiler done.
    JCompiler ready.
    Joseph

  • Program to arrange 4 strings in ascending order .

    can any one gimme the code to arrage 4 strings in ascending order.

    create an internal table with a field of  character type of sufficient length..
    Now append the fields one after one.
    Use sort Table option to get the Required result.
    Code.
    Report XYZ.
    data : begin of t_table occurs 0 ,
             field(255) type c,
           end of t_table.
    field = 'abc'.
    append field.
    field = 'adcg'.
    append field.
    field = 'afeter'.
    append field.
    field = 'afar'.
    append field.
    sort t_table .
    Thanks and regards
    sharma Nittala
    Message was edited by:
            nsk sharma

  • Apple TV sorts my photos only in ascending order, how can I change so the most recent EVENTS appear first?

    Apple TV sorts my photos only in ascending order, how can I change so the most recent EVENTS appear first?

    I'm looking for an answer to this, too, since I have thousands of Events, and so scrolling down to the bottom every time I want to show my newest photos makes it almost unusable.

  • The sort field is not used when ordering multiple cds in one alumn folder, how do I correct this?

    It is using the track number and not the sort order field.  The reason I have multiple cds in one alumn is because they are books on cd.

    Sorry for the typo my "b" key was not working correctly.
    The sort field is not used when ordering multiple cds in one albumn folder, how do I correct this?  It is using the track number and not the sort order field.  The reason I have multiple cds in one albumn is because they are books on cd.

  • [iOS][Your Music] Album sort by artist is out of order

    After the 3.4.0.684 update for IOS, the album sort by artist is out of order. It looks like the sort is only factoring in the first letter in the sort as seen below. Can the old sort methodology be put back in.   

    Updated: 2015-07-08

  • Is it possible to sort Mac Mail Rules into alphabetical order?  I have in excess of 50 rules and everytime I want to add to a rule, such as "delete incoming" I have to go through the entire list to find it.

    Is it possible to sort Mac Mail Rules into alphabetical order?  I have in excess of 50 rules and everytime I want to add or amend a rule, such as "delete incoming" I have to go through the entire list to find it.  I have tried clicking on the heading "Description" but it does not sort.  Any assistance would be greatly appreciated

    Hi,
    According to your description, my understanding is that use CMAK to configure split tunneling on VPN clients, traffic to specified devices can be routed via their own default gateway.
    If the manually added route entries all have default metric and interface, clients will select one by the default routing rule, can’t select one of them according to clients’ own conditions. So, I am afraid that CMAK can’t implement the function which you need.
    A blog described about How to configure split tunneling on VPN clients using CMAK, for your reference:
    http://blogs.technet.com/b/rrasblog/archive/2007/06/11/split-tunnelling-using-cmak.aspx
    Best Regards,
    Eve Wang 
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Recently I downloaded photos from an sd card. When the download was complete all photos were loaded in a random fashion completely out of order.This is the first time it has ever happened this way. downloaded same card to iPhoto and all photos were in ord

    Recently I downloaded photos from an sd card. When the download was complete all photos were loaded in a random fashion completely out of order.This is the first time it has ever happened this way. downloaded same card to iPhoto and all photos were in order. Help needed. Am working on a job that needs immediate attention and HDR images out of order are impossible to deal with.

    Thanks for your help. The out of numerical order comes before the actual import begins. It happens when first uploaded to Lightroom and prior selection of of photos to imported to the catalog.

  • Unable to sort profit center as ascending & Decending order in KE80 & KE30

    Hi,
    When viewing KE30/KE80 reports and navigating by a field such as profit centre, appear to be unable to sort in ascending/descending order.
    e.g. run a KE80 Report: i.e. ZPC-9000 & i.e. variant SMKT, and execute the report click on "Profit Center" under the navigation line to navigate it out to the right. Then click on the magnify glass next to the PC number (should bring up the list of all available PCs, 1259 entries found).
    From this pop-up box, unable to sort the PCs by ascending/descending order regardless of what you click.Also unable to sort the Long Text by ascending/descending order regardless of what you click
    Can anyone pls help on the above issue.We have to apply any note for this???.
    Thanks & Regards
    Mani

    Dear Mani,
    you can sort the entries by right-clicking on the column header and chosing the sorting order in the appearing menu.
    Cheers,
    Daniela

  • I spent ages renaming and sorting my holiday photos in correct order but when uploaded to print they reverted to the original name and order? How can I stop this happening?

    I spent ages renaming and sorting my holiday photos in correct order but when uploaded to print they reverted to the original name and order? How can I stop this happening?

    When you "rename" a photo in iPhoto you're adding a Title to the shot, not renaming the file. This si quite standard metadata in photography, but it appars that it's getting lost in the upload/at Snapfish process.
    You can use the Titles as filenames if you export using the File -> Export command. It's one of the options in the export dialogue. You can upload the exported items.
    Regards
    TD

  • Sorting app on ipad2 in alpha order

    Sorting apps on ipad2 in alpha order yes or no

    Settings > General > Reset > Reset Home Screen Layout may do it in alphabetical order (not sure whether the built-in apps will be shown first) - I've never tried it.

  • Random alphanumeric string

    Hi,
    I need one function which generates a Random alphanumeric string which I want to use as a primary key value. So it must be unique too.
    Something similar to sys_guid in oracle, However I need length of the string fixed to be 6. sys_guid is not helpful as it generates 32 characters long string.
    Can somebody help please?
    Thanks in advance!
    RK

    You can find many examples by doing a search on this forum:
    Alphanumeric sequence number generator

  • How to get string in reverse order?

    Hi I have line as follows...
    String line = "officer.Bangalore, ind",corp\user,passwordAdapter;I want to get the out put of string in reverse order....
    passwordAdapter,corp\user, "officer.Bangalore, ind" please help on code to get this output....
    I tried with using StringBuffer class but it reversing the content of string but not order of string..
    thank in advance....
    Jags

    srry for that...
    lets assume the above is line from file and storing in a string variable..
    In that case.. how can i reverse the order of string(line)...
    i know it should be like this..
    String line = "\"officer.Bangalore, ind\",corp\user,passwordAdapter";plz do the needfull...
    thanks,
    jags

Maybe you are looking for