I need help on a sorting array method()

I'm working on a program that can do a calculation for a swimming event where there will be no more than 200 paticipants. The swimmers that signed up first for the race will be swimming in the last heat.They swim in a pool with 7 lines.The swimmer that signed up first ( and so has the lowest sign up time)swimms in line 4,the swimmer that signed up second ( and so has the second lowest sign up time)swimms in line 5, and the swimmer that signed up after that in line 3.
Which meens that the lines are filled as follow:
line 1 time 7
line 2 time 5
line 3 time 3
line 4 time 1
line 5 time 2
line 6 time 4
line 7 time 6
When the last heat is filled, the heat before the last one is filled after the same pattern and so on, so that the first heat is filled last.
Now, I have written a class that can sort the times from the lowest to the highest, but how do I write a method that can sort the swimmers into the heats and the right lines??
public class SwimmingEvent
private String name;
private int birthYear;
private int number;
private double signUpTime;
private Swimmer[] record;
private int numberOfSwimmers;
public SwimmingEvent()
name = "No record";
birthYear = "No record";
number = "No record";
signUpTime = 0;
public SwimmingEvent(String initialName, int initialBirthYear,
int initialNumber, double initialSignUpTime)
set(initialName, initialBirthYear, initialNumber, initialSignUpTime);
public void set(String newName, int newBirthYear, int newNumber, double newSignUpTime)
name = newName;
birthYear = newBirthYear;
number = newNumber;
signUpTime = newSignUpTime;
public void readInput()
System.out.print("Indtast sv�mmerns navn:");
name = SavitchIn.readLine();
System.out.print("Indtast �rgang:");
birthYear = Savitch.readLine();
System.out.print("Indtast l�bsnummer:");
number = SavitchIn.readLine();
System.out.print("Indtast tid for anmeldelse:");
signUpTime = SavitchIn.readLineDouble();
public void getFigures()
System.out.println("Indtast antalet af sv�mmer:");
numberOfSwimmers = Savitch.readLineInt();
record = new Swimmer[numberOfSwimmers];
int i;
for (i = 0; i < numberOfSwimmers; i++)
record[i] = new Swimmer();
System.out.println("Indtast data for sv�mmer: " + (i+1));
record.readInput();
System.out.println();
public static void sort(double[] a)
int index, indexOfNextSmallest;
for (index = 0; index < a.length - 1; index++);
indexOfSmallestNumber = indexOfSmallest(index, a);
interchange(index, indexOfNextSmallest, a);
private static void interchange(int i, int j, int[] a)
int temp = a[i];
temp = a[i];
a[i] = a[j] = temp;
private static int indexOfSmallest(int startIndex, int[] a)
int min = a[startIndex];
int indexOfMin = startIndex;
int index;
for (index = startIndex + 1; index < a.length; index++)
if (a[index] < min)
min = a[index];
indexOfMin = index;
return indexOfMin;
public void writeOutput()
public String getName()
return name;
public int getBirthYear()
return birthYear;
public int getNumber()
return number;
public double getSignUpTime()
return signUpTime;

Now, I have written a class that can sort the times from the lowest to
the highest, but how do I write a method that can sort the swimmers into
the heats and the right lines??Once you have a working general sort algorithm, issues like this come down to how you make your comparisons between elements. So what you want to do is write your sort code so that the comparison code is modular. (for example, using a class to express comparisons, so you can swap out comparison classes). Then whatever your requirements for sorting elements are, you can achieve them by writing the right comparison code and leaving your sort alone.
This is how Java's core libraries do it, by the way. See:
http://java.sun.com/j2se/1.4.1/docs/api/java/util/Comparator.html
I'm assuming this is your homework. If it's not, then you shouldn't be writing your own sort routines -- use the ones java provides. See the API.

Similar Messages

  • I need help on displaying parallel arrays

    I have created 3 one dimentional arrays and need to pass that array to a method and within the method the program should be able to accept an input from the user. The input should be matched with an array subscript value. I after, I need to display only the array subscript values of the matching input and the subscript values of 2 more parallel arrays
    I need to be able to display only the values of the matching subscripts
    like be able to display the subscript [3]which is a match with the input and the subscript [3] from the other 2 arrays.
    Can someone please help me?

    I have created 3 one dimentional arrays and need to
    pass that array to a method and within the method the
    program should be able to accept an input from the
    user. one array, or all arrays? either way do you have problems in passing them into a method? if so are you famililar with parameter passing and java syntax?
    The input should be matched with an array
    subscript value. traverse the subscript and do this:
    for(int i=0; i<=myarray.length; i++)
    if (myarray[i] = intergerPassed)
    //do whatever
    //eg. System.out.println("matched on "+i);
    //or System.out.println("other arrays have values at this subscript"+ myarray2[i]+" and "+myarray3);
    I after, I need to display only the
    array subscript values of the matching input and the
    subscript values of 2 more parallel arrays
    I need to be able to display only the values of the
    matching subscripts
    like be able to display the subscript [3]which is a
    match with the input and the subscript [3] from the
    other 2 arrays.
    Can someone please help me?

  • Need help in the String Format method

    really need help in string.Format method. I would like to show the s in two digit numbers.
    for example:
    if s is below 10 then display *0s*
    the expecting result is 01,02,03.. 09,10,11....
    I tried this method, somehow i got the errors msg. pls advise. thx.
    public void setDisplay(String s) {
    String tmpSS=String.format("%02d",s);
    this.ss.setText(tmpSS);
    Edited by: bluesailormoon on May 19, 2008 10:30 AM

    Apparently, you expect the string to consist of one or two digits. If that's true, you could do this:String tmpSS = (s.length() == 1) ? ("0" + s) : s; or this: String tmpSS = String.format("%02d", Integer.parseInt(s));

  • Need help on an assignment using methods.

    The assignment I'm working on uses methods to input an integer and a character and then output a hollow square of the size of the integer and made up of the character entered. This is what I have so far, I'm not quite sure how to fill in the methods....
    import java.util.Scanner; //For scanner class
    public class Methods
    {public static void giveInstructions()
         //instructions
         {System.out.println("Enter a character and an integer. A hollow square of size n times n made up of the character" +
              " will be constructed.");
    public static int getSize (Scanner kbd)
         int size;
         Scanner kbd = new Scanner (System.in);
         System.out.println("     Enter the size: ");
         size = kbd.nextInt();
    public static char getCharacter (Scanner kbd)     
         System.out.println("Enter the Character: ");
         final char ch;
         ch = kbd.nextLine();
    public static void drawSquare(int size, char ch)
    public static void drawSolidLine( int size, char ch )
           String s;
            for( int i = 0; i < size ; i++ )
                    // ADD ch       
           System.out.println( s );
    public static void drawHollowLine( int size, char ch )
                String s = "";
                // add char to s   
               for( int i = 0 ; i < ( size - 2) ; i++ )
                       s = s + " ";
               // Add char to s
              System.out.println( s );
    }I would appreciate any kind of help!

    > I'm really confused. I can't think of anything that I
    would need to write under the main method because
    everything that I need would be under the other
    methods.
    I assume you're replying to me(?). Did you compile and run my example? What is it you don't understand about it? I see your methods are all static so you could do something like this:
    public class Test {
        public static void printA() {
            System.out.println("A");
        public static void printB() {
            System.out.println("B");
        public static void printSomething(String s) {
            System.out.println(s);
        public static void main(String[] args) {
            Test.printA();
            Test.printB();
            Test.printSomething("AB");
    }

  • Need Help! Passing an array of objects to a method, dont understand

    Hi, i need to make a method called public Server[] getServers() and i need to be able to see if specific server is available for use.
    I have this so far:
    public abstract class AbstractServer
    protected String serverName;
    protected String serverLocation;
    public AbstractServer(String name,String location)
    this.serverName=name;
    this.serverLocation=location;
    public abstract class Server extends AbstractServer
    public Server(String name,String location)
    super(name,location);
    public class CreateServers
    Server server[];
    public CreateServers()
    public Server create()
    for(int i=0; i<10; i++)
    server=new Server(" ", " "); //i was going to fill in something here
    return server;
    OK NOW HERE IS THE PROBLEM
    i have another class that is supposed to manage all these servers, and i dont understand how to do the public Server[] getServers(), this is what i have tried so far
    public class ServerManager()
    public Server[] getServers(Server[] AbstractServer)
    Server server=null; //ok im also confused about what to do here
    return server;
    in the end i need this because i have a thread class that runs the servers that has a call this like:
    ServerManager.getServers("serverName", null);
    Im just really confused because i need to get a specific server by name but i have to go through AbstractServer class to get it
    Any help?

    thanks for replying...
    ok ill remove the Server.java one to be
    public class Server extends AbstractServer
         public Resource(String name,String locaton)
              super(name,location);
    ok so inside ServerManager.java i should have something like
    ArrayList servers;
    public ServerManager()
    servers=new ArrayList();
    ok but i still dont get how to use that in a method
    say if i put it like this
    public getServers()
    //populate server list in here??????
    ok im still lost...

  • Somebody pleaes help me for sorting arrays...

    Hello.
    I have a problem like this. (http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/APCSL27-1-7.html)
    public class Item implements Comparable
    private int myId;
    private int myInv;
    public Item(int id, int inv)
    myId = id;
    myInv = inv;
    public int getId(){ )
    public int getInv(){ }
    public int compareTo(Object otherObject){ }
    public boolean equals(Object otherObject){ }
    public String toString(){ }
    public class Store
    private Item[] myStore;
    public Store(String fileName) { }
    public void displayStore()
    public String toString(){ }
    public void doSort() { }
    private void quickSort(Item[] list, int first, int last)
    private void loadFile(String inFileName)
    The first line of file50.txt contains the number of id/inventory integer pairs listed on subsequent lines. The idea behind the data type item is the simulation of an item in a store, nearly all of which use a bar code for identification purposes. For every item in a store we keep track of an id value and an inventory amount. So file50.txt looks like this:
    50
    3679 87
    196 60
    17914 12
    18618 64
    2370 65
    etc. (for 45 more lines)
    Each id value in file50.txt will be unique.
    Assignment:
    Write a program that solves the following sequential events:
    loads the data file, file50.txt, as a collection of Item types maintained in a Store object
    sorts the data using quickSort
    prints the data , now in increasing order based on the id field of an Item object
    The printing should add a blank line after every 10 items in the output. Include a line number in the output. For example:
    Id Inv
    1 184 14
    2 196 60
    3 206 31
    4 584 85
    5 768 85
    6 2370 65
    7 3433 5
    8 3679 87
    9 4329 64
    10 5529 11
    11 6265 58
    12 6835 94
    13 6992 76
    14 7282 73
    15 8303 90
    16 9267 68
    etc.
    You will need to complete the getId(), getItem(), compareTo(), equals() and toString() methods for the Item class.
    You will need to complete the Store() constructor, displayStore(), loadFile(), quickSort() and toString() methods for the Store class.
    That's the assigned project.
    this is a side story. I'm a highschooler, and my teacher always hangs out on the internet, teaching nothing. and like this, he just print some problems from the internet and give it to the students. is there a handout about lesson? no. is this always been like this? yeah...
    I have no idea how to right a method called getId(), getInv(), etc...
    would anybody please... please help me?
    p.s.
    the file50.txt is
    on http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/file50.txt
    quicksort is in
    http://www.sum-it.nl/QuickSort.java here.
    somebody please... help me out...

    this is a side story. I'm a highschooler, and my
    teacher always hangs out on the internet, teaching
    nothing. and like this, he just print some problems
    from the internet and give it to the students. is
    there a handout about lesson? no. is this always been
    like this? yeah...
    I have no idea how to right a method called getId(),
    getInv(), etc...
    Well along with the F coming to you for your little assignment I also give you an F for creative writing. This is a shoddy attempt. Why not try something new. Like I live in a mountain town and could not get to school to attend class for three weeks because an avalanche closed the pass.. or my cat peed on my keyboard and I had to get a new one but I couldn't afford it so I don't have enough time left now to figure out myself.
    I dunno. Lot's of ideas.
    Nobody cares about your little sob story. If your teacher is in fact this bad then you should have taken it up with the school administration long ago. It might not be too late to do so. But truth or not it's not going to sucker somebody in to doing your homework for you.
    If you want to learn then do the tutorials until you are capable of completing the assignment. If you have specific questions then help can be given. I don't know what I'm doing is NOT a specific question.

  • Somebody please help me for sorting arrays!!

    Hello.
    I have a problem like this. (http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/APCSL27-1-7.html)
    public class Item implements Comparable
    private int myId;
    private int myInv;
    public Item(int id, int inv)
    myId = id;
    myInv = inv;
    public int getId(){ )
    public int getInv(){ }
    public int compareTo(Object otherObject){ }
    public boolean equals(Object otherObject){ }
    public String toString(){ }
    public class Store
    private Item[] myStore;
    public Store(String fileName) { }
    public void displayStore()
    public String toString(){ }
    public void doSort() { }
    private void quickSort(Item[] list, int first, int last)
    private void loadFile(String inFileName)
    The first line of file50.txt contains the number of id/inventory integer pairs listed on subsequent lines. The idea behind the data type item is the simulation of an item in a store, nearly all of which use a bar code for identification purposes. For every item in a store we keep track of an id value and an inventory amount. So file50.txt looks like this:
    50
    3679 87
    196 60
    17914 12
    18618 64
    2370 65
    etc. (for 45 more lines)
    Each id value in file50.txt will be unique.
    Assignment:
    Write a program that solves the following sequential events:
    loads the data file, file50.txt, as a collection of Item types maintained in a Store object
    sorts the data using quickSort
    prints the data , now in increasing order based on the id field of an Item object
    The printing should add a blank line after every 10 items in the output. Include a line number in the output. For example:
    Id Inv
    1 184 14
    2 196 60
    3 206 31
    4 584 85
    5 768 85
    6 2370 65
    7 3433 5
    8 3679 87
    9 4329 64
    10 5529 11
    11 6265 58
    12 6835 94
    13 6992 76
    14 7282 73
    15 8303 90
    16 9267 68
    etc.
    You will need to complete the getId(), getItem(), compareTo(), equals() and toString() methods for the Item class.
    You will need to complete the Store() constructor, displayStore(), loadFile(), quickSort() and toString() methods for the Store class.
    That's the assigned project.
    this is a side story. I'm a highschooler, and my teacher always hangs out on the internet, teaching nothing. and like this, he just print some problems from the internet and give it to the students. is there a handout about lesson? no. is this always been like this? yeah...
    I have no idea how to right a method called getId(), getInv(), etc...
    would anybody please... please help me?
    p.s.
    the file50.txt is
    on http://www.sfusd.edu/schwww/sch697/depts/math/simon/ICTJAVA/WebLessons/APCSL27/file50.txt
    quicksort is in
    http://www.sum-it.nl/QuickSort.java here.
    somebody please... help me out...

    well you're really going to have to at least do a quick skim of:
    http://java.sun.com/docs/books/tutorial/getStarted/index.html
    And also how to use a browser and browse the API Docs
    especially for: Comparable
    You'll also get flamed for just posting a Homework assignment with no evidence of your own attempts to solve it, OR for not formatting the code with
    [ c o d e ] [ / c o d e ]
    I suppose you get some points if you answer some of the questions?
    Try the easy parts first:
    Complete the methods of the class Item
    Ignore the deliberate Typos in the assignment
    see how you have the class members defined already like:
    private int myId;                         // The guy couldn't be bothered to document his code
    private int myInv;                       // So you will have to.......document itlook at this:
    public int getId() {}As it is the compiler will just say : Missing method body, or declare abstract...
    Your job is to guess what it should do from the 'signature'
    It must return an int and that should be related to Id neh?
    So try things like:
         @return the value of the myId field.
    public int getId()
              return       this.myId;      // return myId would do as well
         Sets the value of myId field
         @param  newId   the new Id to set.
      public void setId( int newId )
           this.myId = newId;             // the old value is replaced with the new
      }do the rest of the simple obvious methods.
    You will get some marks and improve your confidence with simple Java
    Read The API doc on Comparable Interface:
    Decide Carefully how you want to "Order" Objects of type Item.
    In this case this will probably depend first on myId and then subsequently on myInv
    The Comparable interface helps Sorting methods decide qhich object comes first when sorting.
    you will need ssomething like this.
         Implements Comparable - Read the API
    public int compareTo( Object o ) throws ClassCastException, NullPointerException
        if( o == null )
             throw new NullPointerException("Blah blah blah");
       if( !( o instanceof Item ) )
              throw new ClassCastException("Apples and Oranges!");
      Item  item = ( Item ) o;  // Cast o to an Item so it can be checked
      if( this.getId()  < item.getId() )
             return -1;                         // Signal that "this"is less than o
      if ( this.getId() > item.getId() )
            return 1;
      // here both items have the same  myId field
    if( this.getInv() < item .getInv() )
             return -1;
    if( this.getInv() > item.getInv() )
           return 1;
      return 0;                     // they are at the same sort order
    }You use that method like:
      Item a;
      Item b;
      if( a.compareTo( b ) < 0 )
          //blah blah
      }To write the equals method read the API it is similar to compareTo()
    To Read The file : Search on this forum for reading a file line by line.
    Check the API.
    ALso if you have installed Java:
    There are many examples of how to do this in the demo directory
    Even one on QuickSort ---
    So plug away..................

  • Need help implementing Radix sort to handle negative values

    Hi !
    I'm in desperate need for some help here...
    I've been struggling with this Radix sort algorithm for some time now. It sorts positive integers very well, and very fast, but it cant handle negative values. Is there anyone who can help me improve this algorithm to also sort negative integer values?
    I need it to be as fast or even faster then the current one, and it has to be able to sort values in an array from address x -> y.
    Here's what I have so far
    /** sorts an int array using RadixSort (can only handle positive values [0 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0, bits = 8;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   for (int p = start; p < stop; ++p) {
                        int key = (a[p] & mask) >> rshift;
                        ++cntarray[key];
                   for (int i = 1; i < cntarray.length; ++i)
                        cntarray[i] += cntarray[i-1];
                   for (int p = stop-1; p >= start; --p) {
                        int key = (a[p] & mask) >> rshift;
                        --cntarray[key];
                        b[cntarray[key]+start] = a[p];
                   int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }I think it can be solved by offsetting all positive values the with the number of negative values found in "a" during the last run through the main for loop (as the last (or first) 8 bits in an 32 bit integer contains the prefix bit (first bit in an 32 bit integer), 0 for positive value, 1 for negative).
    Thanks in advance !
    /Sygard.

    ah, beautiful !
    /** sorts an int array using RadixSort (can handle values [-2^31 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   if(rshift == 24){
                        for (int p = start; p < stop; ++p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
                   else{
                        for (int p = start; p < stop; ++p) {
                             int key = (a[p] & mask) >>> rshift;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = (a[p] & mask) >>> rshift;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }That's what I ended up with - and it works !
    Thanks a million !!

  • Need help in changing this simple method

    This method searches an inventory vector for an object that wants to delete. It works successfully for the first occurence of the object....ignores the other occurences...
    If I have three titles "Mash" it deletes the first one only ...I need to delete all of teh occurences....please help in improving this method... this method returns true if deleted succesfully, otherwise it returns false... your help is very much appreciated.
    public boolean deleteMovie(MovieItem movie)
    {     MovieData aMovie = new MovieData( queryTitle(movie.getTitle()) );     
              if ( isEmpty() || aMovie.getMovieSpecs() == null )
                   return false;
              MovieData actualMovie = null;
              int i = 0;
              boolean found = false;
              while( i < inventory.size() && !found )
              {     actualMovie = (MovieData)inventory.elementAt(i);
              if ( actualMovie.getMovieTitle().equals( aMovie.getMovieTitle() ) )
              found = true;
              else
              i++;
              if (found && notRented( actualMovie.getMovieSpecs() ) )
              {     inventory.removeElementAt(i);
                   return true;
              else
              {     return false;

    removeElementAt removes only one element from the vector. If you want to remove N items from a vector you need to call removeElementAt N times. But you currently call it only once.
    Here's your code formatted a bit more nicely:public boolean deleteMovie(MovieItem movie) {
        MovieData aMovie = new MovieData(queryTitle(movie.getTitle()));
        if (isEmpty() || aMovie.getMovieSpecs() == null)
            return false;
        MovieData actualMovie = null;
        int i = 0;
        boolean found = false;
        while (i < inventory.size() && !found) {
            actualMovie = (MovieData) inventory.elementAt(i);
            if (actualMovie.getMovieTitle().equals(aMovie.getMovieTitle()))
                found = true;
            else
                i++;
        if (found && notRented(actualMovie.getMovieSpecs())) {
            inventory.removeElementAt(i);
            return true;
        } else {
            return false;
    }As you can see, "inventory.removeElementAt(i);" is not in the loop

  • Need help with a reverse number method

    hey all..
    i have this program which should return the integer reversed ..
    i have done this program using methods.. but the problem is if the
    number endes with 0 when it reversed the output doesn't contain the number 0
    for example:
    input
    123450
    output
    54321
    where before the 5 there should be 0
        This program that reads an integer and then calls a method
          that receives an integer and returns the integer with its digits reversed.
          Main prints the resulting integer.
       import java.util.Scanner; // program uses class Scanner
        class Sh9q4
           // main method begins execution of Java application
           public static void main( String args[] )
          // create Scanner to obtain input from command window
             Scanner input = new Scanner( System.in );
             int number; // The number entered by the user
             System.out.println("Enter an integer"); // prompt for input
             number = input.nextInt(); // read the the integer
             reverse (number); // print the method reverse
          } // end method main
           public static void reverse ( int num )
             int lastDigit; // the last digit returned when reversed
             int reverse = 0;
             do
                lastDigit = num % 10;
                reverse = (reverse * 10) + lastDigit;
                num = num / 10;
             while (num > 0);
             System.out.println("The integer with its digits reversed " + reverse); // print the integer reversed
          }// end method reverse
       } // end class Sh9q4thanks for your help :)

    If you need the leading zero to display, then you will have to do as Keith recommended and convert the input number to a String, then reverse that String and print it as a String.
    A number is a number is a numerical value, and there is no difference between the value of 054321 and 54321 except when written as a literal, when the first is an octal, and the second a decimal, value.
    If you are still confused, plug in these few lines of code and run them:String str = "012345";
    int x = Integer.parseInt (str);
    System.out.println(str);
    System.out.println(x);db

  • I need help with a Object Array

    I am having trouble and this maybe really simple seeing that I am fairly new to java but I have text that is being broken down in to preset part with those parts stored in Object arrays.
    Now I also have a object array inside my object array. Within the second object array are the broken down parts of the text and I want to compare this text with another string so for example this is what I am trying
    boolean found = false;
    for (int i = 0; i < FirstObjectArray.length ;i++)
         Object[] SecondObjectArray = (Object[]) FirstObjectArray;
         if(SecondObjectArray[0] == "string")
              found = true;
              break;
         else
              found = false;
    }Help would be very appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    astlanda wrote:
    Sure, you're right.
    [public boolean equals(Object obj)|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#equals%28java.lang.Object%29]
    sharkura said all the OP needs at the moment. I just wanted to clarify a bit why You don't use == 99.999% of the time with objects, and never with String.
    I have argued elsewhere in these forums that it is inappropriate to tell anyone that you never use == to compare objects. This has not always been accepted. I have, on rare occasions, known experienced developers to blindly compare two objects with equals(), and cite the professor that taught them, 15 years iin the past, that object references are never compared using ==, but always with equals().
    However, the cases where == is appropriate and equals() is not are indeed rare, but not, in my experience, non-existent. In my statement, I probably exaggerated. And String is a case where I can probably accept that you will probably never go wrong with equals(). If the String has been pooled (see String::intern()), you can actually use either. From the javadocs: "*It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.*"
    ¦ {Þ                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help/hints/tips with a method for connect 4 game.

    Hi!
    I'm currently trying to get my "movepiece"-method to make it so that players can only drag a piece into the empty square at the bottom row, and if the square is not empty the method will move up one row and check if it's empty if not, repeat until
     6 are checked if no one is empty then move is invalid.
    I've been trying out while loops and for loops but i think i might set the wrong conditions for exiting the loop...
    Here the code for the method without any loops simply adds pieces.
            /// <summary>
            /// Method that performs the actual move.
            /// The old piece gets overrun by the attacking piece. 
            /// The attacking piece's position becomes null.
            /// </summary>public Piece[,] MoveAttackpiece(int[,] changearray)
    int origX = changearray[0, 0];
    int origY = changearray[0, 1];
    int targetX = changearray[1, 0];
    int targetY = changearray[1, 1];
    pieceArray[targetX, targetY] = pieceArray[origX, origY]; //swap
    return pieceArray;
    The game is using winforms and a 2D array(pieceArray)to draw the game board
    I'm using a Constants class for declaring the height and width of the board, which the pieceArray is based on, Namely const int BOARDESIZEx and BOARDERSIZEy.
    And while i'm at it when i did different loops for tryng to make the piece move down/up (based on if a square in bottom row was empty or not) the program crashes and i get the "Null Reference Exception unhandled"
    at this part in the game.CS (the earlier code reside in a class named Squares.cs)
    if (changearray != null)
    //Building string to print (split over several rows for readability but also to avoid calculations)
    Piece attackpiece = pieceArray[changearray[1, 0], changearray[1, 1]];
    string message = "";
    if (move % 2 == 1) message += "TURN " + move / 2 + ":\r\n"; //integer division, as there are two draws per turn
    message += attackpiece.Name + ": "; //Walker:
    message += IntegerToChar(changearray[0, 1]); //Walker: A
    message += (changearray[0, 0] + 1) + " - "; //Walker A1 -
    message += IntegerToChar(changearray[1, 1]); //Walker A1 - B
    message += (changearray[1, 0] + 1); //Walker A1 - B2
    if (move % 2 == 0) message += "\r\n"; //blank row inserted after each completed turn
    Board.PrintMove(message);
    I've tried making
    While(piecearray[targetX, targetY]!=null)
    pieceArray[targetX, targetY]==pieceArray[targetX, targetY +1];
    return array;
    but that didn't work and i don't really know how to make the game start at bottom row.
    I appreciate any help or tips on how to get this to work since it's the only thing left for making the game work as intended.
    Cheers and thanks for reading.
    PS: if there's anything you wonder just ask and i'll explain as much as i can.
    Regards Gabbelino
    Student at the University of Borås, Sweden

    Let's look at what's wrong with the following code.
    While(piecearray[targetX, targetY]!=null)
    pieceArray[targetX, targetY]=pieceArray[targetX, targetY +1]; // I assume the "==" in your post above was a typo.
    Suppose, for the sake of argument, that targetX is 2 and targetY is 3, and that pieceArray[2,3] is not null. The line inside the loop will then become...
    pieceArray[2,3] = pieceArray[2, 4];
    ...and this line will keep being executed as long as pieceArray[2,3] is not null, which if pieceArray[2,4] is not null will be forever (infinite loop).
    I suspect that your loop should look something like this...
    for(int i = 0; i < BOARDSIZEy; i++)
    // Look for the first available square in the target column.
    // When found, set the piece on that square then break out.
    if(pieceArray[targetX, i] == null)
    pieceArray[targetX, i] = pieceArray[origX, origY];
    break;

  • Need Help to delet sort key! Please help!

    Hi,
    I have a problem in the following program.
    Source Code:
    t-belnr  = bsid-zuonr.
    SPLIT t-belnr at '#' into wk_belnr wk_x_belnr.
    CLEAR t-belnr.
        t-belnr  = wk_belnr.
        t-xblnr  = bsid-belnr.
        IF t-belnr NE space.
          s-belnr      = t-belnr.
        ELSE.
          t-belnr      = t-xblnr.
          s-belnr      = t-xblnr.
        ENDIF.
    IF t-xblnr NE space.                                    "WD041005a
          s-xblnr      = t-xblnr.                               "WD041005a
        ELSE.                                                   "WD041005a
          s-xblnr      = t-belnr.                               "WD041005a
        ENDIF.                                                  "WD041005a
        WHILE s-xblnr(1) EQ '0'.                            "INS MG130606
          SHIFT s-xblnr LEFT.                               "INS MG130606
        ENDWHILE.                                "INS MG130606
    In the final ALV.
    If first colum (t-zuonr) (sort key for the document )is blank, the document need to be deleted.
    Question:
    How can I write the code to deleted the t-zuonr when it is space?
    Please help!!!
    Thank you!!

    Try as below:
    DELETE <itab> WHERE <fld> IS INITIAL.
    i.e
    DELETE t WHERE zuonr IS INITIAL.
    Kind Regards
    Eswar

  • NEED HELP!! creating a method to search records from a data.dat file

    i am having a lot of trouble trying to create a method for searching records from a data.dat file as a contacts application i am using (for) and (if) together and getting the same error messages saying a ")" is needed when it doesn't and illegal start of expression can anyone help! on letting me know how you create search methods! thanks

    public static void search_records()
              System.out.println("Please Enter a Surname (* for all):");
              user_surname = data_input.next();
              System.out.println("Please Enter a firstname (* for all):");
              user_firstname = data_input.next();
              for (int i = 0; i < number_of_records; i++)
                   if(user_surname.compareTo(lastName) || user_surname.compareTo(*));
                             if(user_firstname.compareTo(firstName[i]) || user_firstname.compareTo(*));
                                  system.out.print("Result:",number_of_records);

  • Need help with returning an array of object

    hello, i've been trying to make a method that returns bot ha boolean and a colour for a render for a Jtable and the code for the method is:
         public Object[] isHighlightCellsWithColour(int xInternal, int colInternal) {
              Object[] returnWithTwoValue;
              boolean isHighLight = false;
              returnWithTwoValue = new Object[2];
              returnWithTwoValue[0] = isHighLight;
              returnWithTwoValue[1] = null;
              if (colourPassed == true && this.foundDupeInternal > -1) {
                   for (int c6 = 0; c6 < foundDupeInternal; c6++) {
                        if (this.rows[c6] == xInternal && this.cols[c6] == colInternal) {
                             isHighLight = true;
                             Color colourToSet = errorColourList[c6];
                             returnWithTwoValue = new Object[2];
                             returnWithTwoValue[0] = isHighLight;
                             returnWithTwoValue[2] = colourToSet;
                             return returnWithTwoValue;
              } else {
                   return returnWithTwoValue;
              return null;
         }and when i go and try to use it at
              check = new Object[2];
              check = isHighlightCellsWithColour(xCurrentlyDrawing, colCurrentlyDrawing);
              boolean z = false;
              try {
                   z = (Boolean) check[0];
              } catch (NullPointerException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              Color x = Color.white;
              try {
                   x = (Color)check[1];
              } catch (NullPointerException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              it gives me a nullpointerexception, which i try to catch, but it STILL gives me that error, i have no clue on how to cast from object back to boolean or colour after they are cast into objects
    or else is there a way to pass two different types of data back from a method? Other than using static variables that is, since that gave me problems, it only draws the first cell in colum that is in error in the colour specified , not the rest...
    thanks for your time
    Edited by: TheHolyLancer on Mar 8, 2008 12:42 AM

    yay that got it working, but the method still only draws the first cell with the colour only, need another way to do this one...
    now comes another puzzeling question, it is giving me an null pointer exception again in:
    System.out.println("setting colour "+ x.getBlue() + " On cell " + xCurrentlyDrawing + colCurrentlyDrawing);when i add that to the part where i set the colour, and colour is set to x (which is a color that is passed down by the method) and this will only run if it is determined that a colour is already passed, but it still gives me null pointer error?
    maybe i'll take this to the swing forum tommrow
    Edited by: TheHolyLancer on Mar 8, 2008 2:17 AM
    Edited by: TheHolyLancer on Mar 8, 2008 2:19 AM

Maybe you are looking for