Int to Char for arraylist quicksort

Hey, i need help as our teacher was decent but he went through the sorting extremely quickly so it was hard to understand. Therefore i need help changing this to a char which reads Strings. It currently reads GPA(int) but i need it to read last names and first names (string ------> chars) here is the code i have:
import java.util.ArrayList;
public class SortGPA {
     private void SortGPA(ArrayList list, int low0, int high0) {
          int low = low0, high = high0;
          if (low >= high) {
               return;
          } else if (low == high - 1) {
               if (((Comparable)list.get(low)).compareTo(list.get(high)) > 0) {
                    Object temp = list.get(low);
                    list.set(low, list.get(high));
                    list.set(high, temp);
               return;
          Object pivot = list.get((low + high) / 2);
          list.set((low + high) / 2, list.get(high));
          list.set(high, pivot);
          while (low < high) {
               while (((Comparable)list.get(low)).compareTo(pivot) <= 0 && low < high) {
                    low++;
               while (((Comparable)list.get(high)).compareTo(pivot) >= 0 && low < high) {
                    high--;
               if (low < high) {
                    Object temp = list.get(low);
                    list.set(low, list.get(high));
                    list.set(high, temp);
          list.set(high0, list.get(high));
          list.set(high, pivot);
          SortGPA(list, low0, low - 1);
          SortGPA(list, high + 1, high0);
     public void sort(ArrayList list) {
          SortGPA(list, 0, list.size() - 1);
}

And for that matter, use increment/decrement assignment operators (like += and -=) instead of verbosely repeating the variable. And if you're going to use character-by-character case conversion, use the methods in Character don't do it like a C programmer circa 1982. And if this is anything other than a homework assignment, use encryption code provided in the JDK; don't reinvent it.

Similar Messages

  • Typecasting int into char

    I've got a method I'm working on that looks like this:
    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
    randomInt = generator.nextInt();
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    What I'm trying to do here is create a randomly generated password that consists of five characters. Password_Length is a static variable set to 5. I'm having a problem typecasting the randomInt into a character. Everytime I do this, my display comes back as 'boxes' for each character. If anyone can help, it'd be appriciated.

    private static String generatePassword()
    String pass = "";
    int randomInt;
    char a;
    for(int i = 1; i <= PASSWORD_LENGTH; i++)
                  randomInt = (int)(((double)('z'-'a'))*java.lang.Math.random());
                  if(java.lang.Math.random()<0.5)
                      randomInt -= ('a'-'A');
    a = (char)randomInt;
    pass = pass + a;
    System.out.print(pass);
    return pass;
    }

  • Int to Char...I don't know what the problem is here

    Everything compiles fine here, and if I print out the "encryption" variable I get what looks like it would be right, converted into chars, but when I try to convert the int to char(my char variable for that is 'w'), my compiler freaks out, I don't even know what it's doing it doesn't give me an error, but sometimes it prints out nothing but sometimes it prints out "puTTypUTtypuTTYPUtty" ...why is it doing that and what is wrong with what I am doing?.
    public class encrypt
    public static void main(String[] args)
    String plainText = "hello, my name is christy.";
    String keyWord = "nice to meet you";
    int encryption = 0;
    char ch = 'a';
    char c = 'a';
    int encryptor = 0;
    int charCode;
    int sum = 0;
    char w;
    int i = plainText.length();
    int j = plainText.length();
    int[] plain = new int;
    int[] key = new int[j];
    for(i=0; i<plainText.length(); i++)
    ch = plainText.charAt(i);
    charCode = (int)ch;
    if(charCode > 97 && charCode < 122)//make lowercase
    {charCode = charCode - 97;}
    if(charCode > 65 && charCode < 90)
    {charCode = charCode - 65;}
    plain[i] = charCode;
         for(j=0; j<keyWord.length(); j++)
    c = keyWord.charAt(j);
    int chCode = (int)c;
    if(chCode > 97 && chCode < 122)
    {chCode = chCode - 97;}
    if(chCode > 65 && chCode < 90)
    {chCode = chCode - 65;}
    key[j] = chCode;
    encryption = (plain[i] + key[j]) % 26;
    w = (char)encryption;
    System.out.print(w);

    And for that matter, use increment/decrement assignment operators (like += and -=) instead of verbosely repeating the variable. And if you're going to use character-by-character case conversion, use the methods in Character don't do it like a C programmer circa 1982. And if this is anything other than a homework assignment, use encryption code provided in the JDK; don't reinvent it.

  • Need Hex conversion to char for 4 digits.

    I need to read a file in and translate some of the characters into integers. I need the hex value from the character. Problem is, when using Cp850 which is the encoding of the file, some characters show as ? instead of the proper character.
    A simple output shows the problem where only 4 digit hex values will not appear correctly. You can view the character set and values at the following URL http://www.microsoft.com/globaldev/reference/oem/850.htm
    Here is a simple app to show the problem.
    public class EncodingTest {
         public static void main(String[] args) throws Exception {
              String encoding = "Cp850"; //args[ 0 ];
              byte[] b = new byte[256];
              for (int i = 0; i < 256; i++)
                   b[i] = (byte)i;
              byte c[] = new byte[1];
              String x = new String(b, encoding);
              for (int i = 0; i < x.length(); i++) {
                   c[0] = b;
                   if (x.charAt(i) != i)
                        System.out.println(i + " -> " + (int)x.charAt(i) + "->" + (new String(c, encoding)));
    How to I get character 176 for example to show correctly? I tried to post the output from the app but all of the characters showed as ?.

    Well, if you want to convert int or char values to hex, just do the following:
    Integer.toHexString(int value);
    Now, about your charset problem, I tried it and found out that you will definetly not be able to print strange characters in DOS.
    I'll show you my example, it might help you; it prints out good in my computer...
    public class EncodingTest {
        public static void main(String[] args) throws Exception {
            String encoding = "Cp850"; //args[ 0 ];
            byte[] b = new byte[256];
            for (int i = 0; i < 256; i++)
                b[i] = (byte) i;
            byte c[] = new byte[1];
            String x = new String(b, encoding);
            for (int i = 0; i < x.length(); i++) {
                c[0] = b;
    if (x.charAt(i) != i)
    System.out.println(i + " -> " + Integer.toHexString((int)x.charAt(i)) + "-> " + (int)x.charAt(i) + "->" + (char) i + "->" + (new String(c, encoding)));

  • From int to char...

    Got a nice little problem: I have an int (e.g. int i = 111). This should be transformed into the appropriate ASCII-Code char (or UNICODE-char, if only this is possible). Sounds easy but I didn't manage it.
    In desperate need for help... :-)
    Hannibal_
    Thanx!

    Have you ever tried to cast an int to char? I've tried it for hours now but I didn't get it right. There is no problem to specify a char by giving it an int value (char c = 111) but to cast an int to char. It's not possible to do it like this:
    char c;
    int i = 111;
    c = i;
    Thanx!

  • How to read char() for bit data DB2's type in Oracle?

    Hello,
    I am developing an application (from JDeveloper) to operate with two data base. In one hand threre is Oracle and in the other one DB2 (AS400).
    I am trying to read a DB2'sfield with the "char() for bit data" type from Oracle, but I can't read it.
    I have trying:
    rset.getObject(1) -->[B@1a786c3
    rset.getBinaryStream(1) --> java.io.ByteArrayInputStream@1a786c3
    rset.getAsciiStream(1) --> java.io.ByteArrayInputStream@2bb514
    rset.getCharacterStream(1) -->java.io.StringReader@1a786c3
    Do you have any solution to see the value of this type of field?
    Thank you and regards

    I have to synchronize unidirectionally from the Oracle database to DB2. And I'd like to save the information of the record of DB2 prior to the update operation.
    And here is where the problem arises for me, because when I try to read from Java with the connection established on DB2 is unable to interpret the information. While there are no problems from Oracle to consume the information, it happens that DB2 field types are not common with Oracle, such as char () for bit data. From what I could find the equivalent in Oracle would be raw (), but since Java is possible to read this type of information... And this is my doubt, it is necessary to do any type of cast or to do a special view to retrieve this information?

  • INT. HDs for MPro in Europe

    Greetings Forum,
    I need some help finding INT.HDs in Europe. Specifically Spain, but online in Europe works too.
    What I'm looking for -
    INT. HD for MacPro 2.66, more than 500gigs in size, good for video editing in non-RAID configuration. Source material is DV.
    I would consider 2 - 400gig drives in a RAID Configuration, but I'd prefer to put only 1 drive because this is for 1 project only.
    I've found this site and it looks OK. Never dealt with them so if anyone has, please let me know.
    http://www.tig-spain.com
    Thanks in advance for any help,
    Paz
    P-Book 1.5, 17" 2gsRAM   Mac OS X (10.4.6)   FCStudio

    Yeah, I've been reading this forum page since/before I ordered my MPro and noticed Ned was here as well. Actually hoped he'd throw something down.
    Thinking of going with 2 of the WD5000KS. (What the project can afford now)
    Wasn't planning on RAIDing them, but thinking about it.
    For now, they'll be pretty much dedicated to this one project. But for the future, thinking I could archive the material to an EXT. drive and have a 1TB INT. RAID.
    At that point possibly getting another and making it 1.5TBs.
    Any thoughts on this that you'd like to share?
    Peace

  • Convert from int to char

    Hi,
    How can I convert from an int to char?

    The challange is to convert from int to String without using any API or automatic conversionWoah, what a challenge ! Why ?
    Anyway, what about a recursive call and switch statement. Something likepublic String intToString(int n) {
        if(n<0) {
            return "-"+intToString(-n);
        if(n<10) {
            return getStringDigit(n);
        else {
            return intToString(n/10) + getStringDigit(n%10);
    private String getStringDigit(int n) {
        switch(n) {
            case 0:
                return "0";
            // etc.
    }

  • V3.0, NLS_LENGTH_SEMANTICS byte vs. char for CREATE TABLE

    Hi,
    When creating a new table (via "New Table" or "Data Load ...")
    NLS_LENGTH_SEMANTICS of table columns are always in byte even when NLS_LENGTH_SEMANTICS
    is set to char for the instance (and so as default for all sessions) and has not explicitly changes for the current session.
    Is there a way to change this behavior or could this be a gebnerell problem in 3.0.
    I would like SQL Developer to use the standard settings of the instance as long as I don't set it different for a session.
    Please give me a littel hint how to solve this issue.
    Thanks in advance.
    Andre
    --2011/07/15-------------------------------------------------------------------------------------------
    Hello,
    I'm not sure wether or not this is a too complicated or just as silly question.
    However it's still an issue for me.
    It would be great if someone could at least confirm or refuse it.
    Hoping for an answer- Thank you again!
    Andre
    Edited by: andreml on Jul 15, 2011 2:10 AM
    Edited by: andreml on Jul 15, 2011 2:11 AM

    Hi,
    If you click on any given table in the Connections view, an object viewer opens for that table. Its column tab lists all columns with attributes for column_name, data_type, and so on. The data_type info includes the length semantics, e.g., VARCHAR2(30 BYTE).
    Regards,
    Gary Graham
    SQL Developer Team

  • Is there any default size for ArrayList

    The default capacity of Vector is 10.
    Is there any default size for ArrayList ??
    Vector v = new Vector();
    System.out.println("==> "+v.capacity()); // output is ==> 10
    java.util.List alist = new ArrayList();
    System.out.println("==> "+v.capacity()); // here the out put is ==> 0
    Regards
    Dhinesh

    No default size for arraylist.initially it's zero.
    I think u r comparing capacity with a size those two are different.
    Size- represents number of elements in the array.
    capacity- the capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
    it depends on the ensureCapacity() method in the arraylist.

  • Necesito saber cual es la instrucion que me convierte un int a char es decir lo contrario a la instrucion atoi ya que necesito convertir el entero a cadena para utilizar ese dato en la instrucion SetCrtlval

    Necesito saber cual es la instruccion en cvi que convierte int a char

    Usa sprintf(char Destino, const char Formato, origen_de_datos), que esta en la libreria ANSI C. Es una funcion general que genera un string de chars con cualquier tipo de datos.
    Debes declarar un char Destino del largo necesario para que contenga todo el numero (aprox. 6 caracteres para un int). El char formato es del tipo "%d" para un entero
    Ej
    int Entero;
    char EnteroConvertido[6];
    sprintf(EnteroConvertido,"%d",Entero);

  • Finding int or char value

    Does anyone knows if finding a Numeric value is much faster/same
    as finding
    a value by char:
    For example: If I have a table with ID field which is numeric
    and I need to
    find all ID's where ID>1000
    comparing to
    I have a char status field with value "ACTIVE" and I want all
    status WHERE
    status = "ACTIVE".
    Is the first operation much better?
    Does the char finding operation is done Lexicography (by
    comparing each
    character)?
    Boaz

    The two operations you describe are not comparable so it is not
    possible to answer your question: these sort of things depend on
    so many different things - indexes, number of distinct keys,
    size of table, etc.
    If you rephrase your question to ask:
    is it quicker to use numbers or characters viz
    WHERE status = 'ACTIVE'
    versus
    WHERE status = 2
    then I have heard that numeric searches are supposed to be faster
    but I think that's folklore. I haven't seen any evidence that it
    makes the slightest bit of difference in a well-tuned database.
    (I'd be interested in any info to the contrary.) As a developer
    I find character-based codes easier, because you don't have to
    remember eg whether 2 means 'Active' or 'Cancelled'.
    rgds, APC

  • Int to char - char to int

    I have 2 methods.
    The first method takes an int from 0-256 and casts it to a char and then places the char in a string:
    cCryptedString [iLoop] = (char) iCryptedValue;
    The second method reads the string and casts each character from it into an int.
    iPassStringValue = (int) aString.charAt(iLoop);
    If the iCryptedValue in the 1st method is > 127 and < 150 (because that's as far as they will go at the moment), the casting of that int (i.e. 145) to a char results in a ? being placed in cCryptedString[iLoop].
    When the 2nd method reads the string and encounters the ? placed by the first method, the casting of that char to an int results in a 63 (the ascii value of a ?) instead of the original 145.
    This was not a problem until I installed and ran WebLogic 6.0 sp2 using jdk 1.3 on a Windows 2000 machine. It is working fine under WebLogic 5.1 using jdk 1.2.2.
    Any ideas?
    Thanks,
    Mark

    Here is the 1st method:
    public String encryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iCryptedValue = 0;
    char cCryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iCryptedValue = iPassStringValue + iEncryptKeyValue;
    if (iCryptedValue > 255)
    iCryptedValue = iCryptedValue - 256;
    cCryptedString [iLoop] = (char) iCryptedValue;
    return new String(cCryptedString);
    Here is the 2nd method:
    public String decryptString(String aString) {
    int iPassStringValue = 0;
    int iEncryptKeyValue = 0;
    int iDecryptedValue = 0;
    char cDecryptedString [] = new char[aString.length()];
    for (int iLoop = 0; iLoop < aString.length(); iLoop++) {
    iPassStringValue = (int) aString.charAt(iLoop);
    iEncryptKeyValue = (int) sEncryptKey.charAt(iLoop);
    iDecryptedValue = iPassStringValue - iEncryptKeyValue;
    if (iDecryptedValue < 0)
    iDecryptedValue = iDecryptedValue + 256;
    cDecryptedString [iLoop] = (char) iDecryptedValue;
    return new String(cDecryptedString);
    Thanks!!

  • Using bytes or chars for String phonetic algorithm?

    Hi all. I'm working on a phonetic algorithm, much like Soundex.
    Basically the program receives a String, read it either char by char or by chunks of chars, and returns its phonetic version.
    The question is which method is better work on this, treating each String "letter" as a char or as a byte?
    For example, let's assume one of the rules is to remove every repeated character (e.g., "jagged" becomes "jaged"). Currently this is done as follows:
    public final String removeRepeated(String s){
                    char[] schar=s.toCharArray();
              StringBuffer sb =new StringBuffer();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(schar!=schar[i+1]){
                        sb.append(schar[++i]);//due to increment it wont work for 3+ repetions e.g. jaggged -> jagged
              sb.append(schar[lastIndex]);
              return sb.toString();
    Would there be any improvement in this computation:public final String removeRepeated(String s){
              byte[] sbyte=s.getBytes();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(sbyte[i]==sbyte[i+1]){
                        sbyte[++i]=32; //the " " String
              return new String(sbyte).replace(" ","");
    Well, in case there isn't much improvement from the short(16-bit) to the byte (8-bit) computation, I would very much appreciate if anyone could explain to me how a 32-bit/64-bit processor handles such kind of data so that it makes no difference to work with either short/byte in this case.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You may already know that getBytes() converts the string to a byte array according to the system default encoding, so the result can be different depending on which platform you're running the code on. If the encoding happens to be UTF-8, a single character can be converted to a sequence of up to four bytes. You can specify a single-byte encoding like ISO-8859-1 using the getBytes(String) method, but then you're limited to using characters that can be handled by that encoding. As long as the text contains only ASCII characters you can get away with treating bytes and characters as interchangeable, but it could turn around and bite you later.
    Your purpose in using bytes is to make the program more efficient, but I don't think it's worth the effort. First, you'll be constantly converting between {color:#000080}byte{color}s and {color:#000080}char{color}s, which will wipe out much of your efficiency gain. Second, when you do comparisons and arithmetic on {color:#000080}byte{color}s, they tend to get promoted to {color:#000080}int{color}s, so you'll be constantly casting them back to {color:#000080}byte{color}s, but you have to watch for values changing as the JVM tries to preserve their signs.
    In short, converting the text to bytes is not going to do anywhere near enough good to justify the extra work it entails. I recommend you leave the text in the form of {color:#000080}char{color}s and concentrate on minimizing the number of passes you make over it.

  • How to change int to char?

    hie was wondering if anyone could help me
    i want to take an integer (lets say int y = 9)
    and change it to char x = y . is it possible?

    Doesn't work.
    public class intToChar {
            public static void main( String[] args ) {
                    int i = 10;
                    char c = (char) i;
                    System.out.println("Int is " + i);
                    System.out.println("Char is " + c);
    [/code/
    Above code prints:Int is 10
    Char is
    I've looked in the online API documentation for Character and Integer and found nothing that appears to do what you want to do. I actually wonder if this is possible in core java or if you have to pull some unicode chicanery? Eagerly awaiting reply from someone who knows...
    Maduin

Maybe you are looking for