Compare and sort problem

Code:
import java.io.*;
import java.text.NumberFormat;
public class Account implements Comparable
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.030; // interst rate at 3%
public String acctNumber;
private double balance;
public String name;
// Sets up the account by defining its owner, account number
// and initial balance.
public Account (String owner, String account, double initial)
     name = owner;
     acctNumber = account;
     balance = initial;
// Validates the transaction, then deposits the specfied amount
// into the account. Returns the new balance.
public double deposit (String name, String phone, double amount)
     if (amount < 0) // deposit value is negative
     System.out.println ("!!! Can not deposit negative amount.");
     else
     balance = balance + amount;
     return balance;
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
public double withdraw (double amount)
if (amount < 0 ) // withdraw value is negative
     System.out.println ("!!! Amount " + "(" + (amount) + ") " + "is not valid " + "(" + (balance) + ")");
else
     if (amount > balance) // withdraw value exceeds balance
     System.out.println ("!!! Amount " + "(" + (amount) + ") " + "excedes balance " + "(" + (balance) + ")");
     else
     balance = balance - amount;
return balance;
// Adds interest to the account and returns the new balance.
public double addInterest ()
     balance += (balance * RATE);
     return balance;
// Returns the current balance of the account.
public double getBalance()
     return balance;
// Returns customers name.
public String getName()
     return name;
// Retruns the account number.
public String getAccountNumber()
     return acctNumber;
public int compareTo (Object other)
     int result;
     if (name.equals(((Account)other).name))
     result = acctNumber.compareTo(((Account)other).acctNumber);
     else
     result = name.compareTo(((Account)other).name);
     return result;
// Returns a one-line description of the account as a string.
public String toString()
     return (name + "\t" + acctNumber + "\t" + fmt.format(balance));
public class Bank
private int count = 0;
private Account[] customer;
private int custTotal = 0;
private int index;
public Bank(int customerNum)
customer = new Account[customerNum];
custTotal = customerNum;
public int add(String owner, String account, double initial)
if (findAccount(owner, account) == 0)
customer[count] = new Account(owner, account, initial);
count++;
else
     System.out.println("\n*** Account " + "(" + owner + ", " + account + ") " + "already exists...");
return count+1;
public void deposit (String name, String phone, double amount)
if (findAccount(name, phone) == 1)
customer[index].deposit(name, phone, amount);
System.out.println (">>> customer " + "(" + name + ", " + phone + ") " + " depositing $" + (amount));
else
System.out.println ("*** customer " + "(" + name + ", " + phone + ") " + " not found");
public void withdraw(String name, String phone, double amount)
if (findAccount(name, phone) == 1)
     System.out.println(">>> customer " + "(" + name + ", "
+ phone + ") " + "withdrawing $" + (amount));     
customer[index].withdraw(amount);
else if (findAccount(name, phone) != 1)
System.out.println ("*** customer " + "(" + name + ", " + phone + ") " + "not found");
public int findAccount(String name, String phone)
int result = 0;
for (int i = 0; i < count; i++)
if ((customer.getName() == name)&&(customer[i].getAccountNumber() == phone))
     index = i;
result = 1;
return result;
public void Interest ()
for (int i = 0; i < count; i++)
customer[i].addInterest();
public void list(String display)
System.out.println ();
System.out.println(display);
System.out.println ("Cust ID" +"\t" + "Name" + "\t" + "Phone#" + "\t" + "Balance");
for (int i= 0;i < count; i++)
     System.out.println(i + "\t" + customer[i].toString());
public int compareTo( Object other )
Account tempAccount = (Account) other;
int result;
if (customer[index].equals(((Account)other).getName()))
result = (customer[index].compareTo(((Account)other).getAccountNumber()));
else
result = customer[index].compareTo(((Account)other).getName());
return result;
public void sort(Comparable[] names)
// Sort the array names into increasing order.
int itemsSorted; // Number of items that have been sorted so far.
for (itemsSorted = 1; itemsSorted < names.length; itemsSorted++)
// Assume that items names[0], names[1], ... names[itemsSorted-1]
// have already been sorted. Insert names[itemsSorted]
// into the sorted list.
     Comparable temp = names[itemsSorted]; // The item to be inserted.
int loc = itemsSorted - 1; // Start at end of list.
while (loc >= 0 && names[loc].compareTo(temp) > 0)
names[loc + 1] = names[loc]; // Bump item from names[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
names[loc + 1] = temp; // Put temp in last vacated space.
public class LLBBank
public static void main(String[] args)
int count = 0;
Bank accountList = new Bank (30);
count = accountList.add("Karen", "1234567", 50.00);
count = accountList.add("Karen", "1234444", 50.00);
count = accountList.add("Karen", "1234567", 50.00); // *** Error
count = accountList.add("Jim", "1235555", 200.00);
count = accountList.add("Andy", "1235665", 600.00);
accountList.list("Show beginning balance...");
accountList.withdraw("Karen", "1234567", 30.00);
accountList.withdraw("Karen", "1234567",60); // *** Error
accountList.withdraw("karen chen", "1234567",60); // *** Error
accountList.deposit("Andy", "1234567",60); // *** Error
accountList.deposit("Andy", "1235665",-60); // *** Error
accountList.deposit("Andy", "1235665", 500);
accountList.list("after withdraws and deposits...");
accountList.Interest();
accountList.list("With interest...");
/*accountList.insertionSort();*/
accountList.list("Sorted customer list...");
     /*Bank.insertionSort(accountList);*/
/************ S A M P L E O U T P U T ***************
*** Account (Karen, 1234567) already exists...
Show beginning balance...
Cust ID Name Phone Balance
0 Karen 1234567 50.0
1 Karen 1234444 50.0
2 Jim 1235555 200.0
3 Andy 1235665 600.0
customer (Karen, 1234567) withdrawing $30.0
customer (Karen, 1234567) withdrawing $60.0!!! Amount (60.0) excedes balance (20.0)
*** customer (karen chen, 1234567) not found.
*** customer (Andy, 1234567) not found.
customer (Andy, 1235665) depositting $-60.0!!! Can not deposit negative amount.
customer (Andy, 1235665) depositting $500.0after withdraws and deposits...
Cust ID Name Phone Balance
0 Karen 1234567 20.0
1 Karen 1234444 50.0
2 Jim 1235555 200.0
3 Andy 1235665 1100.0
Add 3% interest to all accounts.With interest...
Cust ID Name Phone Balance
0 Karen 1234567 20.6
1 Karen 1234444 51.5
2 Jim 1235555 206.0
3 Andy 1235665 1133.0
Sorted customer list...
Cust ID Name Phone Balance
0 Andy 1235665 1133.0
1 Jim 1235555 206.0
2 Karen 1234444 51.5
3 Karen 1234567 20.6
********** E N D O F S A M P L E O U T P U T *************/
Problem: I have this assigment for school. I have to do this ATM wannabe program ... but the last two parts they are a problem...
1.to sort the accouts(array) by name
2.when "inputing" an account to compare to existing accounts to make sure that it does no exist ...
directions if needed: compile all and run LLBBank the problem can be see in the output the correct output is in LLBBank.java and also started the compare method
Thank you all

Pls try this code
i already resolved some of the errors
and then post back again the other errors
hope it Helps
gudluck!!!!
import java.io.*;
import java.text.NumberFormat;
public class LLBBank
public static void main(String[] args) {
    int count = 0;
    Bank accountList = new Bank (30);
    count = accountList.add("Karen", "1234567", 50.00);
    count = accountList.add("Karen", "1234444", 50.00);
    count = accountList.add("Karen", "1234567", 50.00); // *** Error
    count = accountList.add("Jim", "1235555", 200.00);
    count = accountList.add("Andy", "1235665", 600.00);
     accountList.list("Show beginning balance...");
     accountList.withdraw("Karen", "1234567", 30.00);
     accountList.withdraw("Karen", "1234567",60); // *** Error
     accountList.withdraw("karen chen", "1234567",60); // *** Error
     accountList.deposit("Andy", "1234567",60); // *** Error
     accountList.deposit("Andy", "1235665",-60); // *** Error
     accountList.deposit("Andy", "1235665", 500);
     accountList.list("after withdraws and deposits...");
     accountList.Interest();
     accountList.list("With interest...");
     /*accountList.insertionSort();*/
     accountList.list("Sorted customer list...");
    /*Bank.insertionSort(accountList);*/
public class Bank {
private int count = 0;
private Account[] customer;
private int custTotal = 0;
private int index;
    public Bank(int customerNum) {
        customer = new Account[customerNum];
        custTotal = customerNum;
    public int add(String owner, String account, double initial) {
        if (findAccount(owner, account) == 0) {
            customer[count] = new Account(owner, account, initial);
            count++;
        } else
            System.out.println("\n*** Account " + "(" + owner + ", " + account + ") " + "already exists...");
        return count+1;
    public void deposit (String name, String phone, double amount) {
        if (findAccount(name, phone) == 1) {
            if(amount>0) {
                customer[index].deposit(name, phone, amount);
                System.out.println (">>> customer " + "(" + name + ", " + phone + ") " + " depositing $" + (amount));
             } else {
               System.out.println("Cannot deposit Amount that is less than or equal to 0");
        } else
            System.out.println ("*** customer " + "(" + name + ", " + phone + ") " + " not found");
    public void withdraw(String name, String phone, double amount) {
        if (findAccount(name, phone) == 1) {
            System.out.println(">>> customer " + "(" + name + ", "+ phone + ") " + "withdrawing $" + (amount));
            customer[index].withdraw(amount);
        } else if (findAccount(name, phone) != 1)
            System.out.println ("*** customer " + "(" + name + ", " + phone + ") " + "not found");
    public int findAccount(String name, String phone) {
      int result = 0;
      for (int i = 0; i < count; i++) {
        if ( customer.getName().equals(name)) {
//&&(customer[i].getAccountNumber().equals(phone))) {
index = i;
result = 1;
return result;
public void Interest () {
for (int i = 0; i < count; i++) {
customer[i].addInterest();
public void list(String display) {
System.out.println ();
System.out.println(display);
System.out.println ("Cust ID" +"\t" + "Name" + "\t" + "Phone#" + "\t" + "Balance");
for (int i= 0;i < count; i++) {
System.out.println(i + "\t" + customer[i].toString());
public int compareTo( Object other ) {
Account tempAccount = (Account) other;
int result;
if (customer[index].equals(((Account)other).getName()))
result = (customer[index].compareTo(((Account)other).getAccountNumber()));
else
result = customer[index].compareTo(((Account)other).getName());
return result;
public void sort(Comparable[] names) {
// Sort the array names into increasing order.
int itemsSorted; // Number of items that have been sorted so far.
for (itemsSorted = 1; itemsSorted < names.length; itemsSorted++) {
// Assume that items names[0], names[1], ... names[itemsSorted-1]
// have already been sorted. Insert names[itemsSorted]
// into the sorted list.
Comparable temp = names[itemsSorted]; // The item to be inserted.
int loc = itemsSorted - 1; // Start at end of list.
while (loc >= 0 && names[loc].compareTo(temp) > 0) {
names[loc + 1] = names[loc]; // Bump item from names[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
names[loc + 1] = temp; // Put temp in last vacated space.
import java.io.*;
import java.text.NumberFormat;
public class Account implements Comparable
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.030; // interst rate at 3%
public String acctNumber;
private double balance;
public String name;
// Sets up the account by defining its owner, account number
// and initial balance.
public Account (String owner, String account, double initial) {
name = owner;
acctNumber = account;
balance = initial;
// Validates the transaction, then deposits the specfied amount
// into the account. Returns the new balance.
public double deposit (String name, String phone, double amount) {
balance = balance + amount;
return balance;
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
public double withdraw (double amount) {
// withdraw value is negative
if (amount < 0 ) {
System.out.println ("!!! Amount " + "(" + (amount) + ") " + "is not valid " + "(" + (balance) + ")");
// withdraw value exceeds balance
} else if (amount > balance) {
System.out.println ("!!! Amount " + "(" + (amount) + ") " + "excedes balance " + "(" + (balance) + ")");
} else
balance = balance - amount;
return balance;
// Adds interest to the account and returns the new balance.
public double addInterest () {
balance += (balance * RATE);
return balance;
// Returns the current balance of the account.
public double getBalance() {
return balance;
// Returns customers name.
public String getName() {
return name;
// Retruns the account number.
public String getAccountNumber() {
return acctNumber;
public int compareTo (Object other) {
int result;
if (name.equals(((Account)other).name))
result = acctNumber.compareTo(((Account)other).acctNumber);
else
result = name.compareTo(((Account)other).name);
return result;
// Returns a one-line description of the account as a string.
public String toString() {
return (name + "\t" + acctNumber + "\t" + fmt.format(balance));

Similar Messages

  • Comparing and sorting raw (NEF) & JPG in LR

    I am interested in importing raw & jpg and then comparing them.
    I want to apply different effects on the raw files to see if I can match or better the jpg files as rendered by the camera
    (I use Nikon).
    Background:
    In the past I have used L:R to view my Nikon NEF files side by side with JPG files from the camera and discovered the amazing versatility of the NEF files at fixing problems in image files and I have therefore always preferred working with RAW files.
    But recently I read a discussion of NikonView (or maybe it was different editing software by Nikon -NX2?) compared to LR wherein several people agreed that Nikon is better at rendering its own NEF files than ADOBE  and they suggested that this was because Nikon engineers know the exact processes (algorithms?) they used to extract & compute the chip data and therefore can better engineer the right editing environment, while Adobe uses a "best guess".  I have no idea whether this is true but it seemed plausible.
    Now I don't own the latest Nikon Software but I wanted to see if I could compare "good" JPGs out of the camera with the image Raw data in LR.
    (Without having to buy the softwareor even open a free trial version)
    The first thing I did was import NEF files and JPG files as separate imports into the same catalog, by changing my import settings.
    It was easy to notice the difference on my screen. (How that translates to print, I dunno.)
    What surprized me was that the JPGs out of the camera immediately looked better than the "Unproessed" NEF files.
    (When properly captured.)  I don't expect them to be as easy to enhance as the raw files though.
    But could I get the Raw file to resemble the JPGS?
    I attempted to set the NEF files to my preferred camera profiles, ( was using portrait setting in camera)
    Even upon eidting my first RAW file I noticed that if I wanted to match the JPGs, I would have to use other adjustments such as contrast, recovery etc.
    I intended to do quick mass-adjustments to the RAW files to see if I could match or beat the JPGs for overall image quality
    I wanted to use Synch to copy those setting to each NEF file.so I set out to sort out the NEF files and JPG files into different groupings and soon discovered I don't know how to do this:  
    IS THERE A QUICK WAY TO SORT / GROUP FILE TYPES IN LR?
    Can I select just the RAW file or just the JPG files?
    I know I can sort files by metadata,  but can't figure out how to sort by extension.
    I realize I can do a workaround by removing the entire folder from the catoalgue and sorting them using windows explorer(XP) and then reimporting them separately.
    But I think there should be an easy way to sort them right in LR.  But I fear there  is not.  Am I right?
    Once I sort them I would be able to mass-apply settings (like contrast adjustments) to one set or another and do some side - by - side comparisons between the RAW files and the JPGs and get the most out of my photos.

    To select by file type, go to the metadata panel in the Library filter (if this isn't showing check
    Show filter bar in the view menu). Then click on any of the meta data panels and select file type. Select the file type you want to see.

  • Filter and sorter Problem

    Hi All
    hope someone can help me in this issue.
    if i build a list view from a table the filters and sorter are working fine, but if i build it using a recordset i get a page has this on it:
    Connection Interrupted
    The document contains no data.
    The network link was interrupted while negotiating a connection. Please try again.
    am i missing something in here ?!?!?
    here is the code for my page..
    http://twayns.150m.com/
    thnx

    -------
    but is ther any reason why the Site Root does not work?
    ADDT (and also DW´s own rudimentary PHP server behaviours) does require this setting for loading "related" files which are relative to the current document -- blame it on the "internal design" if you like, but that´s how it works ;-)
    but when try to filter using any data i got the message (underneath the menus): the table is empty or the filter is too restrictive!!!
    this means that filtering the table didn´t return any records for a reason which ADDT just doesn´t know, that´s why you´re getting this general message returned.
    If you´d like to change this message to something more meaningful like "No records found, please try with another filter setting", open the file "includes/resources/NXT.res.php" and change the line...
    'The table is empty or the filter you\'ve selected is too restrictive.' => 'The table is empty or the filter you\'ve selected is too restrictive.',
    ...to...
    'The table is empty or the filter you\'ve selected is too restrictive.' => 'No records found, please try with another filter setting.',
    Rule of thumb when editing ADDT´s "language files" which are all assembled in that "resources" folder: Only change the text string that´s displayed *after* the => sign, and always make sure not to accidently delete the surrounding ''
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Help: YouTube app Search and sort problem

    Hi,
    I have problem with the YouTube app.  I know there is a search feature, I found the magnifying glass.  However, I have 3 problems.  
    1.) Search Problem:  It won't search everything on YouTube.  I tried seaching, many results would come up from PB's web brower, but it would NOT on the app.  So, what's the point of the app?  
    2.)  After finding the video, the app does not allow me to find/list "video by the same author" or "related video", the "related videos" are not so close "related" compare the web version.
    3.)  When press on the "info" buttom on the app.  The author's describing and format are off.  or not display completely..  
    Would someone please tell me if there will be a fix?  or how to fix it?
    Thanks

    I am not having that problem. Could you post screen shots?
    Be a Shepard and not an iSheep.

  • CompareTo and sorting problems.

    hi all,
    and thanks a lot for your help.
    I have created the following class which as you can see creates an object and can sort an array of such objects
    with respect to the deadline variable using the compareTo method.
    import java.util.Date;
    public class Task {
         Date deadline;
         long runtime;
         public int compareTo (Object obj){
         Date thatDate = ((Task)obj).deadline;
         Date thisDate = new Date(0);
         int k = thatDate.compareTo(thisDate);
         return k;
    I am trying to find a way of sorting the Task objects with respect to the runtime variable but I cannot.
    Can you please make a suggestion?
    Thanks in advance,
    Dennis

    Your compareTo won't work: it doesn't compare the deadlines of the two tasks, but rather the deadline of one task with the fixed Date 1. January 1970. Try this instead (in addition to the advice of the OP):
    public int compareTo(Object obj) {
      Date thatDate = ((Task)obj).deadline; // this will throw an exception if obj is not a Task
      return deadline.compareTo(thatDate.deadline);
      // or: return thatDate.deadline.compareTo(deadline);
    }Also, consider making instance variables private and accessible through accessor methods.

  • [Microsoft][SQL Server Native Client 11.0][SQL Server]The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.  'Items' (OITM) (OITM)

    Dear Experts,
    i am getting the below error when i was giving * (Star) to view all the items in DB
    [Microsoft][SQL Server Native Client 11.0][SQL Server]The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.  'Items' (OITM) (OITM)
    As i was searching individually it is working fine
    can any one help me how to find this..
    Regards,
    Meghanath.S

    Dear Nithi Anandham,
    i am not having any query while finding all the items in item master data i am giving find mode and in item code i was trying to type *(Star) and enter while typing enter the above issue i was facing..
    Regards,
    Meghanath

  • Error in SQL Query The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query

    hi Experts,
    while running SQL Query i am getting an error as
    The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    T2.LineText
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,T2.LineText
    how to resolve the issue

    Dear Meghanath,
    Please use the following query, Hope your purpose will serve.
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    CAST(T2.LineText as nvarchar (MAX))[LineText]
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry --where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,CAST(T2.LineText as nvarchar (MAX))
    Regards,
    Amit

  • How do I fix my problem with Artist and Sort Artist?

    I have all my songs sorted by Artist and because I have songs that feature other artists I use the sort artist field.
    In itunes it all looks fine but when I sync it with my iPod Nano 5th Gen one of the artists names comes up as the artist for all songs.
    Eg. I have 5 B.o.B songs.The Artist field has B.o.B and the featured artist so it looks like -B.o.B feat. Hayley Williams-. The sort artist field along with album artist and sort album artist field are all only B.o.B.
    My problem is that when I sync them onto my iPod all the songs by B.o.B appear under B.o.B feat. Rivers Cumo when I sort by Artist despite this only being the artist for one and all listed with the same format as above. They all also come up with the Artist as B.o.B feat. River Cumo when I play one of the songs.
    Is there anyway to fix this so on my iPod they all appear under B.o.B when sorting by Artist but when I play the song it gives me the artist name? I'd prefer not to have to put the featured artist in the song title.

    This sometimes happens if your MacBook battery is swollen, and pushes on the underside of the trackpad.
    Some users forgot that an alternate input device, like a tablet, does not shut off when set aside -- it continues to provide input at the same time as the mouse you put your hand on.

  • Problems analizing compares and swaps in my algorithims

    What I need to do is analize my sorting algorthims, in terms of the number of compares and swaps. I have about 6 different sorts in one class, a couple of them came from help by, other posters, on this board. And I have a simple file reader in another class that reads a txt file, sorts, then prints, but also prints the numbers of compares, swaps, using varibles from my sorting class.
    The txt file has 64 strings(names of people). Some of the sort I get what seems to me correct, or least close to correct results, but for a couple I"m getting downright strange results. I'm trying to figure out where to put the counting variables so I can get decent results.
    In my quicksort, the results I'm getting is 1 compares 1 swaps, now obviously that's wrong but I'm trying to figure out where to put, the variables to get the correct results.
         public static void quicksort(List data, int first, int last){
                           int lower = first + 1, upper = last;
                           swap(data,first,(first+last)/2);
                           Comparable Bound = (Comparable)data.get(first);
                           while (lower <= upper){
                                while ((((Comparable)data.get(lower)).compareTo(Bound)) < 0)
                                          lower++;
                                while (Bound.compareTo(data.get(upper)) < 0)
                                     upper--;
                                if (lower < upper)
                                     swap(data,lower++,upper--);
                                else lower++;
                           swap(data,upper,first);
                           if (first < upper-1)
                                quicksort(data,first,upper-1);
                           if (upper+1 < last)
                                quicksort(data,upper+1,last);
          public static void quicksort(List data){
                           if (data.size() < 2)
                                return;
                           int max = 0;
                           //find largest data and put at end of data
                           for (int i = 1; i < data.size(); i ++)
                                if (((((Comparable) 
                           data.get(max)).compareTo(data.get(i))) < 0))
                                     max = i;
                           compares++;       // <----------------------- COMPARE
                           swap(data,data.size()-1,max);
                           swaps++;                 //    <--------------------------   SWAP
                           quicksort(data,0,data.size()-2);
    }      The selection sort results give me exactly the same for both compares, and swaps 2016.
    public static void selectionSort (List data)
               int i,j, least;
               final int size = data.size();
               for (i = 0; i < size - 1; i++)
                  for (j = i+1, least = i; j < size; j++)
                       compares++;             //   <-------------------- COMPARE
                 if (((((Comparable) (data.get(j))).compareTo(data.get(least)))) < 0)
                      least = j;
                      swap(data,least,i);
                      swaps++;                         //   <------------------------ SWAP
            Thanks for your help.

    jkc532 wrote:
    .. Is the fact that the CachedJarFile class doesn't attempt to reload the resource when it can't retrieve it from MemoryCache a bug? From your comprehensive investigation and report, it seems so to me.
    ..I've dug as deep as I can on this and I'm at wits end, does anybody have any ideas?Just after read the summary I was tired, so I have some understanding of the effort you have already invested in this (the 'wits' you have already spent). I think you should raise a bug report and seek Oracle's response.

  • Add rows and sort JTable in the same program

    I would like to have a button to add rows to the JTable, but would also like to sort the data within the columns. This program can sort the data prior to clicking the 'add row' button. After I click the button, there is no new row, and I lose the ability to sort the column. Do you have any tips or advice as to what I can do to fix my program? Is it because I have to have the final code for SortFilterModel to work?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              Object[][] data = {
                        {"6", "K"},
                        {"5", "A"},
                        {"1", "Z"}
              String[] columnNames = {
                    "Number",
                    "Letter"
              model = new DefaultTableModel(data, columnNames);
                    //comment out this SortFilterModel line
                    final SortFilterModel sorter = new SortFilterModel(model);
                    //Change sorter to model
              table = new JTable(sorter);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        model.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, row, false, false);
                        table.requestFocusInWindow();
                 //Set up double click handler for column headers and sort
                 table.getTableHeader().addMouseListener(new MouseAdapter(){
                        public void mouseClicked(MouseEvent event)
                          //check for click
                          if (event.getClickCount() < 2) return;
                       //find column of click and
                       int tableColumn = table.columnAtPoint(event.getPoint());
                       //translate to table model index and sort
                       int modelColumn = table.convertColumnIndexToModel(tableColumn);
                       sorter.sort(modelColumn);
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

    I attempted to modify the code in the correct way, but I ran into a problem near the bottom with the model.addRow(rowData); line. It has an error saying it can't find the addRow method. If I take away the model part, it will compile, but it will cause an infinite loop when I push the 'Add Row' button within the program. I didn't expect that to work, and I think it isn't calling the right model.
    I am aware that my code organization and design skills are not very good. I am a fan of basic assembly and low-level hardware languages for the most part.
    Thanks for your advice so far, it has been helpful.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableRowColumn extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         public DefaultTableModel model;
         JPanel buttonPanel;
         JButton button;
         public TableRowColumn()
              Object[][] data = {
                        {"9", "C"},
                        {"5", "A"},
                        {"3", "B"}
              String[] columnNames = {
                    "Number",
                    "Letter"
              model = new DefaultTableModel(data, columnNames);
                    //comment out this SortFilterModel line
                    final SortFilterModel sorter = new SortFilterModel(model);
                    //Change sorter to model
              table = new JTable(sorter);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              //  Add table and a Button panel to the frame
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              button = new JButton( "Add Row" );
              buttonPanel.add( button );
              button.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        sorter.addRow( createRow() );
                        int row = table.getRowCount() - 1;
                        table.changeSelection(row, row, false, false);
                        table.requestFocusInWindow();
                 //Set up double click handler for column headers and sort
                 table.getTableHeader().addMouseListener(new MouseAdapter(){
                        public void mouseClicked(MouseEvent event)
                          //check for click
                          if (event.getClickCount() < 2) return;
                       //find column of click and
                       int tableColumn = table.columnAtPoint(event.getPoint());
                       //translate to table model index and sort
                       int modelColumn = table.convertColumnIndexToModel(tableColumn);
                       sorter.sort(modelColumn);
         private Object[] createRow()
              Object[] newRow = new Object[2];
              int row = table.getRowCount() + 1;
              newRow[0] = Integer.toString( row );
              newRow[1] = LETTERS.substring(row-1, row);
              return newRow;
         public static void main(String[] args)
              TableRowColumn frame = new TableRowColumn();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    class SortFilterModel extends AbstractTableModel{
        public SortFilterModel(TableModel m){
            model = m;
            rows = new Row[model.getRowCount()];
            for (int i = 0; i < rows.length; i++) {
                rows[i] = new Row();
                rows.index = i;
    public void sort(int c){
    sortColumn = c;
    Arrays.sort(rows);
    fireTableDataChanged();
    public Object getValueAt(int r, int c) {
    return model.getValueAt(rows[r].index, c);
    public boolean isCellEditable(int r, int c){
    return model.isCellEditable(rows[r].index, c);
    public void setValueAt(Object aValue, int r, int c){
    model.setValueAt(aValue, rows[r].index, c);
    public int getRowCount() {
    return model.getRowCount();
    public int getColumnCount(){
    return model.getColumnCount();
    public String getColumnName(int c) {
    return model.getColumnName(c);
    public Class getColumnClass(int c){
    return model.getColumnClass(c);
    private class Row implements Comparable {
    public int index;
    public int compareTo(Object other) {
    Row otherRow = (Row)other;
    Object a = model.getValueAt(index, sortColumn);
    Object b = model.getValueAt(otherRow.index, sortColumn);
    if (a instanceof Comparable) {
    return ((Comparable)a).compareTo(b);
    else{
    return a.toString().compareTo(b.toString());
    public void addRow(Object[] rowData) {
    Row[] oldRows = new Row[rows.length];
    for (int i=0; i<rows.length; i++) {
    oldRows[i] = rows[i];
    rows = new Row[rows.length +1];
    for (int i=0; i < oldRows.length; i++) {
    rows[i] = oldRows[i];
    rows[oldRows.length] = new Row();
    rows[oldRows.length].index = oldRows.length;
    addRow (rowData);
    //model.addRow(rowData);
    fireTableDataChanged();
    private TableModel model;
    private int sortColumn;
    private Row[] rows;

  • Quicksort using Comparable can sort out negative value well !!

    man , i have waste another day try to solve this logic problem. It was not easy as what i thought. The Qsort method which i found it on the net and i apply it into my java code .. i do understand his code well , however the result does not sort out well especially negative number or if there is there are small number at the end of the array. Below are some result which i compile .Hope someone can help me , i going crazy soon.
    sample 1:
    Before Soft()
    [93, 50, 34, 24, -48, 27, 45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -37, -48, -71, -95, 11, 16, 2, 24, 27, 34, 45, 50, 51, 60, 93]
    sample 2:
    Before Soft()
    [-93, 50, -34, -24, 48, -27, -45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -24, -27, -34, -37, -45, -71, -93, -95, 11, 16, 2, 48, 50, 51, 60]
    sample 3 ==> this one is correct ;-)
    Before Soft()
    [93, 50, 34, 24, 48, 27, 45, 11, 60, 51, 95, 16, 12, 71, 37, 20]
    After Soft()
    [11, 12, 16, 20, 24, 27, 34, 37, 45, 48, 50, 51, 60, 71, 93, 95]
    import java.util.*;
    import java.lang.Comparable;
    public class QuickSort {
    // static Comparable [] array;
    public QuickSort(){}
    public static void main ( String [] args){
              QuickSort qs =new QuickSort ( );
              Object [] test = new Object [16];
              test[0]="93";
              test[1]="50";
              test[2]="34";
              test[3]="24";
              test[4]="-48";
              test[5]="27";
              test[6]="45";
              test[7]="11";
              test[8]="60";
              test[9]="51";
              test[10]="-95";
              test[11]="16";
              test[12]="-12";
              test[13]="-71";
              test[14]="-37";
              test[15]="2";
              for (int i=0;i<test.length;i++)
              System.out.println(test);
              System.out.println();
    /* Copy the value from the Object [ ]test into Comparable [] array. /*
    Comparable [] array = new Comparable [test.length];
    for(int i=0;i<array.length;i++)
         array [i]=(Comparable) test[i];          
         System.out.println(array[i]); //test if the value is the same as the test Object //
    System.out.println("Before Soft()");
    System.out.println(Arrays.asList(array));
    qs.sort(array); //call sort method to sort the array
    System.out.println("After Soft()");
         System.out.println(Arrays.asList(array));
    * Sorts the array of Comparable objects using the QuickSort algorithm.
    * @param comparable an array of java.lang.Comparable objects
    public void sort(Comparable comparable[]) {
    QSort(comparable, 0, comparable.length - 1);
    * @param comparable an array of java.lang.Comparable objects
    * @param lowInt int containing lowest index of array partition
    * @param highInt int containing highest index of array partition
    static void QSort(Comparable comparable[], int lowInt, int highInt) {
    int low = lowInt;
    int high = highInt;
    Comparable middle;
    // The partion to be sorted is split into two separate sections which are
    // sorted individually. This is done by arbitrarily establishing the middle
    // object as the starting point.
    if (highInt > lowInt) {
    middle = comparable[(lowInt + highInt) / 2];
    // Increment low and decrement high until they cross.
    while (low <= high) {
    // Increment low until low >= highInt or the comparison between
    // middle and comparable[low] no longer yields -1 (ie comparable[low]
    // is >= middle).
    while (low < highInt && (comparable[low].compareTo(middle) < 0)) {
    ++low;
    // Decrement high until high <= lowInt or the comparison between
    // middle and comparable[high] no longer yields 1 (ie comparable[high]
    // is <= middle).
    while (high > lowInt && (comparable[high].compareTo(middle) > 0 )) {
    --high;
    /*switch over */
    if (low <= high) {
    Comparable obj;
    obj = comparable[low];
    comparable[low] = comparable[high];
    comparable[high] = obj;
    ++low;
    --high;
    if (lowInt < high) {
    QSort(comparable, lowInt, high);
    if (low < highInt) {
    QSort(comparable, low, highInt);

    the problem is solve after cos i cast a string variable into the object comparable. The problem is solve after i use cast Integer into the object.
    regards
    st

  • Comparable and Comparator Interface - Collections

    Hi All
    Please let me know when to use Comparable interface and Comparator interface. ?
    Any sort of information is highly appreciable .
    Matt

    Matt wrote:
    @ jverd      
    So, when you googled, and found tutorials, and worked through those tutorials, and read the javadocs for those classes, what in particular did you not understand?If everything would work like that what will be the use of forums like this , It does work like that, for people who aren't lazy. The use of these forums, as indicated by my first reply, is among other things, when you've done your own research, as you should do, and run into something you don't understand.
    so dont try to be smart :(Maybe you should try to be smarter.
    Lets try not to abuse the forum with exchanges like this. The only abuse so far has been you expecting the forum to be a substitute for doing your own research.
    I know how to use Comparable and Comparator but dont know when to use these in a real time application.That statement says nothing about your problem. The only information it carries is that you don't know what the term "real time" means.

  • Comparable and Serializable interfaces

    Hi All,
    I have developed a program in java which implements Comparable and Serializable Interfaces. After, I decided to run the program in J2ME. But later on, I found that MIDP doesn't implement these interfaces.
    Some one can help me how to implement my own interfaces.
    Thank you

    Hi Supareno
    I need urgently your help.
    I developed Java program which works as predicitive text system for my mother tongue.I would like to move from Java to J2ME. But until now I have problems. please can u help me. the following code run in command line.
    I tried to develop my own interfaces as you told me but it doesn't work.
    Help me also for reading and writing text files.
    Thank you
    import java.util.*;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    public class PredText {
    private Vector dict;
    public static final String dictionaryFile = "C:/java/words.txt";
    // convert a string to the corresponding signature
    public static String toNumeric (String word) {
    String lowerWord = word.toLowerCase();
    StringBuffer result = new StringBuffer("");
    for (int i = 0; i < lowerWord.length(); i++) {
    char c = lowerWord.charAt(i);
    if ("abc".indexOf(c) > -1) result.append("2");
    else if ("def".indexOf(c) > -1) result.append("3");
    else if ("ghi".indexOf(c) > -1) result.append("4");
    else if ("jkl".indexOf(c) > -1) result.append("5");
    else if ("mno".indexOf(c) > -1) result.append("6");
    else if ("pqrs".indexOf(c) > -1) result.append("7");
    else if ("tuv".indexOf(c) > -1) result.append("8");
    else if ("wxyz".indexOf(c) > -1) result.append("9");
    else if (" ".indexOf(c) > -1) result.append("9");
    else result.append("?");
    return result.toString();
    // find all the words corresponding to a signature
    public Vector findMatches(String sig) {
    WordSig ws = new WordSig(sig, "");
    WordSig newws;
    Vector results = new Vector();
    int index;
    index = Collections.binarySearch(dict, ws);
    if (index < 0){
    // no matches! :(
    // try to get the string that starts with a substring like ours.
    index=-1-index;
    if (((WordSig)dict.get(index)).getSig().startsWith(sig)) {
    // no word found. we return those starting with the
    // same signature
    newws = (WordSig) dict.get(index);
    results.addElement(newws.getWord().substring(0,sig.length()));
    return results;
    } else{
    //no match
    return results;
    } else {
    // go back to the first match
    while(((WordSig)dict.get(index)).getSig().equals(sig) && index>0)
    index--;
    if (index != 0)
    index++;
    while ((newws = (WordSig) dict.get(index)).equals(ws)){
    results.addElement( newws.getWord() );
    index++;
    return results;
    // intialises the dictionary
    public PredText () {
         String word;
    String sig;
    Vector dict = null;
    // first try to load dict.dat
    try {
    System.out.print("Trying to load dict.dat...");
    FileInputStream fileStream = new FileInputStream("C:/java/dict.dat");
    ObjectInputStream objectStream = new ObjectInputStream(fileStream);
    dict = (Vector) objectStream.readObject();
    fileStream.close();
    System.out.println(" done.");
    }catch (ClassNotFoundException classNotFoundException) {
         System.out.println("Unable to create an object");     
    catch (IOException e) {
    // exception: create the dictionary
    System.out.println("Error. I'm going to recreate the dictionary file");
    try {
    dict = createDict();
    catch (IOException ioe) {
    System.err.println("Error while creating dictionary file. Exiting." + e);
    System.exit(1);
    this.dict = dict;
    // create the dictionary serialised file
    public Vector createDict () throws IOException {
    String word;
    Vector dict = new Vector();
    //open the dictionary file
    System.out.print("Reading the dictionary... ");
    BufferedReader dictFile = new BufferedReader(
    new FileReader(dictionaryFile));
    //insert each word into the data structure
    while ((word = dictFile.readLine()) != null) {
    word = word.toLowerCase();
    dict.addElement(new WordSig(toNumeric(word), word));
    // List list = dict.subList(0, dict.size());
    List list = dict.subList(0, dict.size());
    Collections.sort(list);
    System.out.println("done.");
    System.out.print("Writing the dictionary... ");
    FileOutputStream fileStream = new FileOutputStream("C:/java/dict.dat");
    ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
    objectStream.writeObject(dict);
    objectStream.flush();
    fileStream.close();
    System.out.println("done.");
    return dict;
    public static void main (String args[]) {
         PredText pt = new PredText();
    if (args.length == 0) {
    // no arguments, find the largest clash
         Vector result;
         Enumeration e = pt.dict.elements();
    String currentSig = "";
    String prevSig = "";
    int clash = 0;
    int maxClash = 0;
    String clashSig = "";
    while (e.hasMoreElements()) {
    WordSig ws = (WordSig) e.nextElement();
    currentSig = ws.getSig();
    if (currentSig.equals(prevSig)) {
    // another word with the same signature
    clash ++;
    } else {
    // new signature: check if the previous one led
    // to a maximal clash
    if (clash > maxClash) {
    clashSig = prevSig;
    maxClash = clash;
    clash = 1;
    prevSig = currentSig;
    result = pt.findMatches(clashSig);
    System.out.println("The signature leading to most clashes is "
    + clashSig + " with " + result.size() +
    " number of clashes");
    for (int j = 0; j < result.size(); j++) {
    System.out.println((String)result.get(j));
    } else if ("0123456789".indexOf(args[0].charAt(0)) > -1){
    // numeric input: find the matches for the argument
    Vector result;
    result = pt.findMatches(args[0]);
    for (int j = 0; j < result.size(); j++) {
    System.out.println((String)result.get(j));
    } else {
    // convert each word to the corresponding signature
    for (int i = 0; i < args.length; i++) {
    System.out.print(toNumeric(args) + " ");
    class WordSig implements Comparable, Serializable {
    String word;
    String sig;
    public WordSig (String sig, String word) {
    this.sig = sig;
    this.word = word;
    public String getSig () {
    return this.sig;
    public String getWord() {
    return this.word;
    public int compareTo (Object ws) {
    return sig.compareTo(((WordSig) ws).getSig());
    public boolean equals (Object ws) {
    return sig.equals(((WordSig) ws).getSig());
    public String toString () {
    return sig + ", " + word;

  • Hp LaserJet CP1515n Printer Paper Jam, Cleaning Mode and calibration problem.

    We have Two no. Hp Laser Jet CP1515n Printers,
    We are facing repetatively the following problems.
    Paper Jam, Cleaning Mode and calibration problem. even after hp has replaced that printer twice..
    Pl. help me to sort out the problem.

    after 1 or 2nd page printing it display paper jam problem, after clearing the paper jam it goes in initialization mode. so we have to spent minimum 5 min. for taking one print out...
    Pl. help to solve the problem..

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

Maybe you are looking for

  • I can't  preview svg files in bridge cs6 on mac 10.6.8. Help!

    Hi, I want to know why can't I preview svg files in bridge cs6 on mac 10.6.8. It's really frustrating as an increasing number of Illustrator files are saved in this format and I need to check through a gazillion of them. Help!

  • PO Not updating in POWL

    Hi Experts, Iu2019ve managed to delete a PO, but when I refresh the POWL itu2019s still showing as ordered and canu2019t get it to appear in the deleted PO list. we are having standalone scenario.Could any guide me on this. <<Text removed>> regards s

  • Connecting Yamaha keyboard to iMac through Midi

    Help!! I am trying to connect my keyboard to my iMac (10.5.8) for GarageBand. It is going from Midi out to USB. I went into the Utilities pane and saw the keyboard there. I went into GarageBand under preferences and it stated that it detected 1 midi

  • Airport keep disconnecting every few minutes

    Hi, I don't know why, but my airport keeps disconnecting every few minutes, although it reconnects after that. I'm sure there's no problem with my router since other PCs in my home are fine. It's totally fine when I use my windows in the macbook (via

  • On order stock to be transferred to Unrestricted stock

    Some material was transferred from Plant X to Plant Y. Now this material is lying in On order stock instead of  Unrestricted stock Kindly suggest how this On order stock can be transferred to Unrestricted stock Thanks