Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Java-Help with BubbleSort of Array

  • 27-04-2006 9:27pm
    #1
    Registered Users, Registered Users 2 Posts: 206 ✭✭


    Hi,
    I am in desperate need of some help with this Java application.

    It consists of 5 textfields, a textarea and a Button.

    The user is supposed to be able to input 5 numbers and thenn click on the button and the application should display the five number is sorted order.

    I got as far as getting the numbers to appear on the textarea but they are not sorted and there is no space between the numbers.

    Can anyone help. See code below:


    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;

    public class NumberSorter extends JFrame implements ActionListener{

    private JTextField tf1, tf2, tf3, tf4, tf5;
    private JButton b1;
    private JLabel l1, l2;
    private JPanel panel;
    private JTextArea outputArea;
    int Numbers[]= new int[5];

    public NumberSorter() {

    super("Number Sorter");
    Container contentPane = getContentPane();
    JPanel panel = new JPanel();
    //=========================================================================================================
    // Create Label to give instructions to user
    //========================================================================================================

    JLabel label1 = new JLabel("Please enter a number in each field and click on Bubble Button to sort");
    label1.setVerticalAlignment(JLabel.TOP);



    //========================================================================================================
    // Create TextField area for Output
    //========================================================================================================


    outputArea = new JTextArea(10,25);

    //=============================================================================================================
    // Create five TextFields & One Button and Add Action Listeners
    //=============================================================================================================

    tf1 = new JTextField(5);
    //Align text to center of textfield
    tf1.setHorizontalAlignment(JTextField.CENTER);
    // Initialize the text of the field
    tf1.setText(" ");
    tf1.addActionListener(this );


    tf2 = new JTextField(5);
    tf2.setHorizontalAlignment(JTextField.CENTER);
    tf2.setText(" ");
    tf2.addActionListener(this );




    tf3 = new JTextField(5);
    tf3.setText(" ");
    tf3.setHorizontalAlignment(JTextField.CENTER);
    tf3.addActionListener(this );




    tf4 = new JTextField(5);
    tf4.setHorizontalAlignment(JTextField.CENTER);
    tf4.setText(" ");
    tf4.addActionListener(this );



    tf5 = new JTextField(5);
    tf5.setHorizontalAlignment(JTextField.CENTER);
    tf5.setText(" ");
    tf5.addActionListener(this );



    //Create JButton

    JButton b1 = new JButton("BUBBLE SORT");
    b1.addActionListener(this );

    //=================================================================================================
    // Add Label, TextFields, TextArea and Button to Panel.
    //=================================================================================================
    panel.add(label1);
    panel.add(tf1);
    panel.add(tf2);
    panel.add(tf3);
    panel.add(tf4);
    panel.add(tf5);
    panel.add(b1);
    panel.add( new JScrollPane(outputArea), BorderLayout.CENTER );

    //=================================================================================================
    // Add the panel to the content pane and set window properties
    //==================================================================================================

    contentPane.add(panel);

    setSize(450,300);
    setVisible( true );

    }//end of Sorter constructor

    //===================================================================================================
    // Use String Method to send Bubblesort array to TextArea
    //===================================================================================================



    public void actionPerformed( ActionEvent e ){

    String s1="", s2="", s3="", s4="", s5="";




    s1=tf1.getText();
    Numbers[0]= Integer.parseInt(s1.trim()); //add FIRST number to array here
    s2=tf2.getText();
    Numbers[1]= Integer.parseInt(s2.trim()); //add SECOND number to array here
    s3=tf3.getText();
    Numbers[2]= Integer.parseInt(s3.trim()); //add THIRD number to array here
    s4=tf4.getText();
    Numbers[3]= Integer.parseInt(s4.trim()); //add FOURTH number to array here
    s5=tf5.getText();
    Numbers[4]= Integer.parseInt(s5.trim()); //add FIFTH number to array here


    String output = ("Numbers in original order:\n");

    // append array values to String output

    for ( int counter = 0; counter < 5; counter++ ){

    output += Integer.toString( Numbers[counter] );


    outputArea.setText( output );//output numbers to TextArea

    }//end of for loop


    }//end of ActionEvent



    //===========================================================================================================
    // Instructions to Close Window
    //===========================================================================================================

    public static void main(String args [])
    {

    NumberSorter myFrame = new NumberSorter();
    myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    }


    }//end of class


Comments

  • Registered Users, Registered Users 2 Posts: 763 ✭✭✭Dar


    darabbit wrote:
    output += Integer.toString( Numbers[counter] );

    There's no spaces because you arn't adding any to the output string. Change above line to:
    output += Integer.toString(Numbers[counter]) + " ";

    That will add a space after each number.

    All you have to do now is write a function to perform the bubblesort, and append the sorted array to the output string as well.


  • Registered Users, Registered Users 2 Posts: 206 ✭✭darabbit


    Thanks fot that Dar.

    I had a go at the Bubble Sort and I got 4 compiler errors. Can you see from the code attached what I have left out.
    thanks a mill,
    darabbit

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;

    public class NumberSorter extends JFrame implements ActionListener{

    private JTextField tf1, tf2, tf3, tf4, tf5;
    private JButton b1;
    private JLabel l1, l2;
    private JPanel panel;
    private JTextArea outputArea;
    int Numbers[]= new int[5];

    public NumberSorter() {

    super("Number Sorter");
    Container contentPane = getContentPane();


    //=========================================================================================================
    // Create Panel where components are to be stored
    //=========================================================================================================


    JPanel panel = new JPanel();
    panel.setBackground(Color.pink);//Change background colout to pink
    //panel.setLayout(new GridLayout(5,6 ) );//set layout to GridLayout
    //==========================================================================================================
    // Create Label to give instructions to user
    //==========================================================================================================

    JLabel label1 = new JLabel("Please enter a number in each field and click on Bubble Sort Button to sort");
    label1.setVerticalAlignment(JLabel.TOP);


    //============================================================================================================
    // Create TextField area for Output
    //============================================================================================================


    outputArea = new JTextArea(10,25);
    outputArea.setEditable(false);//Do not allow Textarea to be edited.
    outputArea.setLineWrap(true);//allow wrapping of text


    //=============================================================================================================
    // Create five TextFields & One Button and Add Action Listeners
    //=============================================================================================================

    tf1 = new JTextField(5);
    //Align text to center of textfield
    tf1.setHorizontalAlignment(JTextField.CENTER);
    // Initialize the text of the field
    tf1.setText(" ");
    tf1.addActionListener(this );


    tf2 = new JTextField(5);
    tf2.setHorizontalAlignment(JTextField.CENTER);
    tf2.setText(" ");
    tf2.addActionListener(this );




    tf3 = new JTextField(5);
    tf3.setText(" ");
    tf3.setHorizontalAlignment(JTextField.CENTER);
    tf3.addActionListener(this );




    tf4 = new JTextField(5);
    tf4.setHorizontalAlignment(JTextField.CENTER);
    tf4.setText(" ");
    tf4.addActionListener(this );



    tf5 = new JTextField(5);
    tf5.setHorizontalAlignment(JTextField.CENTER);
    tf5.setText(" ");
    tf5.addActionListener(this );



    //Create JButton

    JButton b1 = new JButton("BUBBLE SORT");
    b1.addActionListener(this );

    //=================================================================================================
    // Add Label, TextFields, TextArea and Button to Panel.
    //=================================================================================================
    panel.add(label1);
    panel.add(tf1);
    panel.add(tf2);
    panel.add(tf3);
    panel.add(tf4);
    panel.add(tf5);
    panel.add(b1);
    panel.add( new JScrollPane(outputArea), BorderLayout.CENTER );

    //=================================================================================================
    // Add the panel to the content pane and set window properties
    //==================================================================================================

    contentPane.add(panel);

    setSize(450,300);
    setVisible( true );

    }//end of Sorter constructor

    //===================================================================================================
    // Use String Method to send Bubblesort array to TextArea
    //===================================================================================================



    public void actionPerformed( ActionEvent e ){

    String s1="", s2="", s3="", s4="", s5="";




    s1=tf1.getText();
    Numbers[0]= Integer.parseInt(s1.trim()); //add FIRST number to array here
    s2=tf2.getText();
    Numbers[1]= Integer.parseInt(s2.trim()); //add SECOND number to array here
    s3=tf3.getText();
    Numbers[2]= Integer.parseInt(s3.trim()); //add THIRD number to array here
    s4=tf4.getText();
    Numbers[3]= Integer.parseInt(s4.trim()); //add FOURTH number to array here
    s5=tf5.getText();
    Numbers[4]= Integer.parseInt(s5.trim()); //add FIFTH number to array here



    String output = ("Numbers in original order:\n");

    // append array values to String output

    for ( int counter = 0; counter < 5; counter++ ){

    output += Integer.toString( Numbers[counter])+ " ";


    outputArea.setText( output );//output numbers to TextArea



    }//end of for loop



    //====================================================================================================
    // BubbleSort Numbers in Array and Display to TextArea
    //====================================================================================================

    if (e.getActionCommand()=="BUBBLE SORT"){ // test if Bubble Sort button was selected


    int Numbers[]= new int[5];

    String output = "Data items in original order\n";

    // append original array values to String output

    for ( int counter = 0; counter < array.length; counter++ )

    output += " " + array[ counter ];

    bubbleSort( array ); // sort array

    output += "\n\nData items in ascending order\n";

    // append sorted\ array values to String output

    for ( int counter = 0; counter < array.length; counter++ )

    output += " " + array[ counter ];

    outputArea.setText( output );


    }//end of ActionCommand


    // sort elements of array with bubble sort

    public void bubbleSort( int array2[] ) {

    // loop to control number of passes

    for ( int pass = 1; pass < array2.length; pass++ ) {

    // loop to control number of comparisons

    for ( int element = 0; element < array2.length - 1; element++ ) {

    // compare side-by-side elements and swap them if first element is greater than second element

    if ( array2[ element ] > array2[ element + 1 ] )

    swap( array2, element, element + 1 );



    }//end of inner for loop

    }//end of for loop

    }//end of BubbleSort

    // swap two elements of an array

    public void swap( int array3[], int first, int second ) {

    int hold; // temporary holding area for swap

    hold = array3[ first ];

    array3[ first ] = array3[ second ];

    array3[ second ] = hold;

    }//end of swap


    }


    }

    }//end of ActionEvent



    //===========================================================================================================
    // Instructions to Close Window
    //===========================================================================================================

    public static void main(String args [])
    {

    NumberSorter myFrame = new NumberSorter();
    myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    }


    }//end of class


  • Registered Users, Registered Users 2 Posts: 19,396 ✭✭✭✭Karoma


    The errors might help
    wrape code in [ code ] tags.


  • Registered Users, Registered Users 2 Posts: 206 ✭✭darabbit


    Sorry, here are the compiler errors:

    [C:\Documents and Settings\Caroline Ryan\My Documents\Software_Dev\Spring06\NumberSorter.java:199: illegal start of expression
    public void bubbleSort( int array2[] ) {
    ^
    C:\Documents and Settings\Caroline Ryan\My Documents\Software_Dev\Spring06\NumberSorter.java:235: ';' expected
    }//end of swap
    ^
    C:\Documents and Settings\Caroline Ryan\My Documents\Software_Dev\Spring06\NumberSorter.java:243: 'class' or 'interface' expected
    }//end of ActionEvent
    ^
    C:\Documents and Settings\Caroline Ryan\My Documents\Software_Dev\Spring06\NumberSorter.java:261: 'class' or 'interface' expected
    ^
    4 errors

    Tool completed with exit code 1]

    Any ideas?


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Because you're code isn't in code tags, it makes it a bit harder to read... so these are guesses based purely on the errors:

    illegal start of expression:
    Did you write your function inside another function? Is your function defined in the usual manner, or did you make a mistake in the syntax of declaring the function?

    ';' expected:
    You left out a ";" somewhere :P Check the lines just above the line indicated in the error messsage.

    As for the other two, they might vanish when you fix the ";" mistake. Always fix your errors from top down when reading the compile error report. Usually when you fix one near the top, it'll fix a load of errors below it.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 206 ✭✭darabbit


    Application is now running. I didn't call the array what I had declared it to be. There was also an extra } .

    Thanks for all your help.
    :)


  • Closed Accounts Posts: 2 tolanaomi


    Hi,

    I Googled Bubble Sort Arrays using JTextFile and I think this code will work for the most part for what I need if I change it to a String but the problem is he had an issue with the bubble sort too. I found the example he used and guess what? It wouldn't compile in jGrasp (which is really nice to use to edit I found out too) either. So what's wrong with the Bubble Sort here? If someone can see it please let me know so I can fix it and then make the changes so my friend can use it for some people's names he needs to enter. Thanks!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    
    public class NumberSorter extends JFrame implements ActionListener{
    
    private JTextField tf1, tf2, tf3, tf4, tf5;
    private JButton b1;
    private JLabel l1, l2;
    private JPanel panel;
    private JTextArea outputArea;
    int Numbers[]= new int[5];
    
    public NumberSorter() {
    
    super("Number Sorter");
    Container contentPane = getContentPane();
    
    
    //=========================================================================================================
    //     Create Panel where components are to be stored
    //=========================================================================================================
    
    
    JPanel panel = new JPanel();
    panel.setBackground(Color.pink);//Change background colout to pink
    //panel.setLayout(new GridLayout(5,6 ) );//set layout to GridLayout
    //==========================================================================================================
    //     Create Label to give instructions to user
    //==========================================================================================================
    
    JLabel label1 = new JLabel("Please enter a number in each field and click on Bubble Sort Button to sort");
    label1.setVerticalAlignment(JLabel.TOP);
    
    
    //============================================================================================================
    //     Create TextField area for Output
    //============================================================================================================
    
    
    outputArea = new JTextArea(10,25);
    outputArea.setEditable(false);//Do not allow Textarea to be edited.
    outputArea.setLineWrap(true);//allow wrapping of text
    
    
    //=============================================================================================================
    //     Create five TextFields    & One Button and Add Action Listeners
    //=============================================================================================================
    
    tf1 = new JTextField(5);
    //Align text to center of textfield
    tf1.setHorizontalAlignment(JTextField.CENTER);
    // Initialize the text of the field
    tf1.setText(" ");
    tf1.addActionListener(this );
    
    
    tf2 = new JTextField(5);
    tf2.setHorizontalAlignment(JTextField.CENTER);
    tf2.setText(" ");
    tf2.addActionListener(this );
    
    
    
    
    tf3 = new JTextField(5);
    tf3.setText(" ");
    tf3.setHorizontalAlignment(JTextField.CENTER);
    tf3.addActionListener(this );
    
    
    
    
    tf4 = new JTextField(5);
    tf4.setHorizontalAlignment(JTextField.CENTER);
    tf4.setText(" ");
    tf4.addActionListener(this );
    
    
    
    tf5 = new JTextField(5);
    tf5.setHorizontalAlignment(JTextField.CENTER);
    tf5.setText(" ");
    tf5.addActionListener(this );
    
    
    
    //Create JButton
    
    JButton b1 = new JButton("BUBBLE SORT");
    b1.addActionListener(this );
    
    //=================================================================================================
    // Add Label, TextFields, TextArea and Button to Panel.
    //=================================================================================================
    panel.add(label1);
    panel.add(tf1);
    panel.add(tf2);
    panel.add(tf3);
    panel.add(tf4);
    panel.add(tf5);
    panel.add(b1);
    panel.add( new JScrollPane(outputArea), BorderLayout.CENTER );
    
    //=================================================================================================
    //     Add the panel to the content pane and set window properties
    //==================================================================================================
    
    contentPane.add(panel);
    
    setSize(450,300);
    setVisible( true );
    
    }//end of Sorter constructor
    
    //===================================================================================================
    //     Use String Method to send Bubblesort array to TextArea
    //===================================================================================================
    
    
    
    public void actionPerformed( ActionEvent e ){
    
    String s1="", s2="", s3="", s4="", s5="";
    
    
    
    
    s1=tf1.getText();
    Numbers[0]= Integer.parseInt(s1.trim()); //add FIRST number to array here
    s2=tf2.getText();
    Numbers[1]= Integer.parseInt(s2.trim()); //add SECOND number to array here
    s3=tf3.getText();
    Numbers[2]= Integer.parseInt(s3.trim()); //add THIRD number to array here
    s4=tf4.getText();
    Numbers[3]= Integer.parseInt(s4.trim()); //add FOURTH number to array here
    s5=tf5.getText();
    Numbers[4]= Integer.parseInt(s5.trim()); //add FIFTH number to array here
    
    
    
    String output = ("Numbers in original order:\n");
    
    // append array values to String output
    
    for ( int counter = 0; counter < 5; counter++ ){
    
    output += Integer.toString( Numbers[counter])+ " ";
    
    
    outputArea.setText( output );//output numbers to TextArea
    
    
    
    }//end of for loop
    
    
    
    //====================================================================================================
    //     BubbleSort Numbers in Array and Display to TextArea
    //====================================================================================================
    
    if (e.getActionCommand()=="BUBBLE SORT"){ // test if Bubble Sort button was selected
    
    
    int Numbers[]= new int[5];
    
    String output = "Data items in original order\n";
    
    // append original array values to String output
    
    for ( int counter = 0; counter < array.length; counter++ )
    
    output += " " + array[ counter ];
    
    bubbleSort( array ); // sort array
    
    output += "\n\nData items in ascending order\n";
    
    // append sorted\ array values to String output
    
    for ( int counter = 0; counter < array.length; counter++ )
    
    output += " " + array[ counter ];
    
    outputArea.setText( output );
    
    
    }//end of ActionCommand
    
    
    // sort elements of array with bubble sort
    
    public void bubbleSort( int array2[] ) {
    
    // loop to control number of passes
    
    for ( int pass = 1; pass < array2.length; pass++ ) {
    
    // loop to control number of comparisons
    
    for ( int element = 0; element < array2.length - 1; element++ ) {
    
    // compare side-by-side elements and swap them if first element is greater than second element
    
    if ( array2[ element ] > array2[ element + 1 ] )
    
    swap( array2, element, element + 1 );
    
    
    
    }//end of inner for loop
    
    }//end of for loop
    
    }//end of BubbleSort
    
    // swap two elements of an array
    
    public void swap( int array3[], int first, int second ) {
    
    int hold; // temporary holding area for swap
    
    hold = array3[ first ];
    
    array3[ first ] = array3[ second ];
    
    array3[ second ] = hold;
    
    }//end of swap
    
    
    }
    
    
    }
    
    }//end of ActionEvent
    
    
    
    //===========================================================================================================
    // Instructions to Close Window
    //===========================================================================================================
    
    public static void main(String args [])
    {
    
    NumberSorter myFrame = new NumberSorter();
    myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    
    }  
    
    
    Here are the compile errors

    ----jGRASP exec: javac -g NumberSorter.java
    
    NumberSorter.java:195: illegal start of expression
    public void bubbleSort( int array2[] ) {
    ^
    NumberSorter.java:195: illegal start of expression
    public void bubbleSort( int array2[] ) {
           ^
    NumberSorter.java:195: ';' expected
    public void bubbleSort( int array2[] ) {
                          ^
    NumberSorter.java:195: ';' expected
    public void bubbleSort( int array2[] ) {
                                        ^
    NumberSorter.java:221: illegal start of expression
    public void swap( int array3[], int first, int second ) {
    ^
    NumberSorter.java:221: illegal start of expression
    public void swap( int array3[], int first, int second ) {
           ^
    NumberSorter.java:221: ';' expected
    public void swap( int array3[], int first, int second ) {
                    ^
    NumberSorter.java:221: <identifier> expected
    public void swap( int array3[], int first, int second ) {
                                   ^
    NumberSorter.java:221: not a statement
    public void swap( int array3[], int first, int second ) {
                                        ^
    NumberSorter.java:221: ';' expected
    public void swap( int array3[], int first, int second ) {
                                             ^
    NumberSorter.java:221: ';' expected
    public void swap( int array3[], int first, int second ) {
                                                         ^
    NumberSorter.java:239: class, interface, or enum expected
    }//end of ActionEvent
    ^
    NumberSorter.java:247: class, interface, or enum expected
    public static void main(String args [])
                  ^
    NumberSorter.java:251: class, interface, or enum expected
    myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    ^
    NumberSorter.java:253: class, interface, or enum expected
    }
    ^
    15 errors
    

    So why is it hating that bubble sort so much?

    Thanks for any and all input on this! I am a newbie so please forgive my ignorance...


  • Registered Users, Registered Users 2 Posts: 2,013 ✭✭✭lynchie


    You know this thread is 5 years old?
    If someone can see it please let me know so I can fix it and then make the changes so my friend can use it for some people's names he needs to enter. Thanks!
    Secondly, You need the code to work for your friend? I suggest your "friend" should use excel to sort some names if that's all he wants to achieve rather than getting you to find some piece of java code to do a sort for him. Or is this an assignment me thinks?:confused:


  • Closed Accounts Posts: 2 tolanaomi


    Yes I know it's an old thread. No he doesn't want to use Excel. No it's not an assignment. Wow I never saw so many haters in my life! I asked a simple question but all I got was 'hate'. Really? If you don't know why do you need to reply? Really - all I wanted to understand was how they fixed it. That was it. I programmed legacy systems for decades and honestly even old school programmers weren't so mean spirited. Please, if you haven't anything nice to say then say nothing at all.


Advertisement