如何手动将元素插入数组并对元素进行排序 [英] How to manually insert elements into the array and sort the elements

查看:67
本文介绍了如何手动将元素插入数组并对元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个JApplet程序,该程序将dvds加载到数组中,并在文本区域中以排序的格式显示它们.我创建了一个名为dvd的类,该类将所有内容加载到数组dvd中.我的课使用的工具可与sort媲美.
我的问题是我无法插入/添加到数组中,但仍然对数组中的元素进行排序
我想知道如何插入dvdz数组,并且仍然对新插入的元素进行排序,而又不影响序列.

这是我的程序代码:

///////////////////////////////////////////////////////////////////

I have developed a JApplet program that loads dvds into array and displays them in a textarea in a sorted format. i have created a class called dvd that loads all the content to array dvd. my class uses implements comparable to sort.
my problem is i cant insert/add into the array and still sort the element in the array
i want to know how do i insert into the array dvdz and still sort the newly inserted element without affecting the sequence.

here''s my program code:

//////////////////////////////////////////////////////////////////

//
// created by NS KHUMALO
//  20702589
//
//
//

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.ListIterator;


public class dvdMain extends JFrame implements ActionListener, ItemListener
{
    private JLabel lblDvdSystemBanner, lblSelectOptions,lblMovieTitle,lblYearOfRelease,lblAgeClassification,lblMovieGenre,lblMovieTime,lblPrice;
    private TextField txtMovieTitle, txtYearOfRelease, txtAgeClassification, txtMovieGenre,txtMovieTime, txtPrice;
    private JButton btnBack, btnBack2, btnAdd;
    private JTextArea txaDisplay;
    private JPanel mainPanel,disPanel,dPanel,rdbPanel,addPanel,txtAreaPanel;
    private JRadioButton rdbLoad, rdbDisplay, rdbAdd, rdbSave, rdbLFile, rdbExit;
    private Font msgF = new Font("Algerian",Font.BOLD,23);


    private static int s = 0;

    private int width, height;

    PrintWriter outputStream;

    Container con = getContentPane();

    dvdClass[] dvds = new dvdClass[99];

         dvdClass dvd1 = new dvdClass("Jaws",1996,"PG 13","Thriller",89);
         dvdClass dvd2 = new dvdClass("Titanic",1997,"PG 13","Drama",90);
         dvdClass dvd3 = new dvdClass("Be cool",2008,"PG 13","comedy",89);
         dvdClass dvd4 = new dvdClass("Hitch",2005,"PG 13","Comedy",90);


         dvdClass[] dvdz = new dvdClass[] {dvd1, dvd2, dvd3,dvd4};

//  ArrayList<dvdClass> dvds = new ArrayList<dvdClass>();

    public static final int H = 400;
    public static final int W = 390;

    public static void main(String [] args)
    {


        dvdMain tb = new dvdMain();
        tb.setBounds(340,120,550,500);

        for(int i=0; i< 20; i++)
        System.out.println("loading...");
        tb.setSize(750,400);
        tb.setVisible(true);



    }
    public dvdMain()
    {
        setTitle("Dvd Records");
        setSize(450,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        dvdMain.setDefaultLookAndFeelDecorated(true);

        mainPanel = new JPanel();
        mainPanel.setLayout(new FlowLayout());

        disPanel = new JPanel();
        disPanel.setLayout(new GridLayout(2,1));

        dPanel = new JPanel();
        dPanel.setLayout(new GridLayout(2,1));

        lblDvdSystemBanner = new JLabel("DVD Booking System");
        lblDvdSystemBanner.setFont(msgF);
        lblSelectOptions = new JLabel("Please select one option from the list");

        dPanel.add(lblDvdSystemBanner);
        dPanel.add(lblSelectOptions);

        disPanel.add(dPanel);

        mainPanel.add(disPanel,"North");

        try
        {

            outputStream = new PrintWriter(new FileOutputStream("dvds.txt",true));

        }
        catch(FileNotFoundException e)
        {
            System.err.println("File not found");
            System.exit(1);
        }

        ButtonGroup rg = new ButtonGroup();

        rdbLoad = new JRadioButton("Load DVD's");
        rdbLoad.addItemListener(this);


        rdbDisplay = new JRadioButton("Display DVD's");
        rdbDisplay.addItemListener(this);
        rdbDisplay.setEnabled(false);

        rdbAdd = new JRadioButton("Add a DVD(s)");
        rdbAdd.addItemListener(this);
        rdbAdd.setEnabled(false);

        rdbSave = new JRadioButton("Save DVD(s)");
        rdbSave.addItemListener(this);
        rdbSave.setEnabled(false);

        rdbExit = new JRadioButton("Exit");
        rdbExit.addItemListener(this);

        rg = new ButtonGroup();
        rg.add(rdbLoad);
        rg.add(rdbDisplay);
        rg.add(rdbAdd);
        rg.add(rdbSave);
        rg.add(rdbExit);

        rdbPanel = new JPanel();
        rdbPanel.setLayout(new GridLayout(6,1));

        rdbPanel.add(rdbLoad);
        rdbPanel.add(rdbDisplay);
        rdbPanel.add(rdbAdd);
        rdbPanel.add(rdbSave);
        rdbPanel.add(rdbExit);

        disPanel.add(rdbPanel);

        lblMovieTitle = new JLabel("Enter movie title: ");
        lblYearOfRelease =new JLabel("Enter year of release: ");
        lblAgeClassification =new JLabel("Enter age classification: ");
        lblMovieGenre =new JLabel("Enter movie genre: ");
        lblMovieTime =new JLabel("Enter movie playing time in minutes: ");

        txtMovieTitle  = new TextField(20);
        txtYearOfRelease  = new TextField(20);
        txtAgeClassification  = new TextField(20);
        txtMovieGenre  = new TextField(20);
        txtMovieTime  = new TextField(20);


        addPanel = new JPanel();
        addPanel.setLayout(new GridLayout(7,2,10,15));

        addPanel.add(lblMovieTitle);
        addPanel.add(txtMovieTitle);
        addPanel.add(lblYearOfRelease);
        addPanel.add(txtYearOfRelease);
        addPanel.add(lblAgeClassification);
        addPanel.add(txtAgeClassification);
        addPanel.add(lblMovieGenre);
        addPanel.add(txtMovieGenre);
        addPanel.add(lblMovieTime);
        addPanel.add(txtMovieTime);


        btnBack = new JButton("Back");
        btnBack.addActionListener(this);

        btnAdd = new JButton("Add");
        btnAdd.addActionListener(this);

        btnBack2 = new JButton("Back");
        btnBack2.addActionListener(this);

        addPanel.add(btnBack);
        addPanel.add(btnAdd);

        txtAreaPanel = new JPanel();
        txtAreaPanel.setLayout(new BorderLayout());

        txaDisplay = new JTextArea(20,20);
        txaDisplay.setBackground(Color.WHITE);
        txtAreaPanel.add(txaDisplay,BorderLayout.NORTH);
        txtAreaPanel.add(btnBack2,BorderLayout.SOUTH);

        addPanel.setVisible(false);
        txtAreaPanel.setVisible(false);
        mainPanel.setVisible(true);

        mainPanel.add(txtAreaPanel);
        mainPanel.add(addPanel);


        setContentPane(mainPanel);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("Back"))
            back();
        else if (e.getActionCommand().equals("Add"))
            addDvd(dvdz);
    }

    public void itemStateChanged(ItemEvent e)
    {
        Object source = e.getSource();
        int select = e.getStateChange();

        if (source == rdbLoad)
                load(dvds);
            else if(source == rdbDisplay)
                display(dvds);
            else if(source == rdbAdd)
                add(dvds);
            else if(source == rdbSave)
                save(dvds);
            else if(source == rdbExit)
                exit();
    }

    /* Clear any existing object that are in the array
     * Create four Book Oject
     * Place them in the array
     */
    public void load(dvdClass[] dvds)
    {
        rdbAdd.setEnabled(true);
        rdbSave.setEnabled(true);
        rdbDisplay.setEnabled(true);
        rdbLoad.setEnabled(false);


        disPanel.setVisible(true);
        txtAreaPanel.setVisible(false);
        addPanel.setVisible(false);

        clearArray();

        s = 3;
     /*
         dvdClass dvd1 = new dvdClass("Jaws",1996,"PG 13","Thriller",89);
         dvdClass dvd2 = new dvdClass("Titanic",1997,"PG 13","Drama",90);
         dvdClass dvd3 = new dvdClass("Be cool",2008,"PG 13","comedy",89);
         dvdClass dvd4 = new dvdClass("Hitch",2005,"PG 13","Comedy",90);

         dvds = new dvdClass[] {dvd1, dvd2, dvd3,dvd4};
         Arrays.sort(dvds);

         for (dvdClass dvd : dvds)
         //  txaDisplay.append("\n "+ dvd.toString());
         System.out.println("THis is**************"+ dvd.toString()+"\n");

         */

         //Arrays.sort(dvds);
         }
          /*    dvdClass dc = new dvdClass(titl,dat);
            movies.add(dc);

            movieT.setText("");
            yearR.setText("");
            time.setText("");


            Iterator itr = movies.iterator();

//       Collection.sort(dvds);

        //JOptionPane.showMessageDialog(null,"load");

    }
    /* Call add Panel
     */
    public void add(dvdClass[] dvds)
    {
        disPanel.setVisible(false);
        txtAreaPanel.setVisible(false);
        addPanel.setVisible(true);
    }
    /* Display all Book's in the array
     */
    public void display(dvdClass[] dvds)
    {

        addPanel.setVisible(false);
        disPanel.setVisible(false);
        txtAreaPanel.setVisible(true);

        txaDisplay.setText("");

        txaDisplay.append(" "+ "MOVIE TITLE"+"\t\t" + "YEAR OF RELEASE" +"\t" + "AGE CLASSIFICATION" + "\t" + "GENRE"+ "\t" + "PLAYING TIME\t\n");


         Arrays.sort(dvdz);

         for (dvdClass dvd : dvdz)
       txaDisplay.append("\n"+ dvd.toString());
      //   System.out.println( dvd.toString()+"\n");

        // display in the text area
        //for (dvdClass dvd : dvds)
    //  for(int i=0;i<=dvds.length;i++)
       // txaDisplay.append("\n "+ dvds[i].getMovieTitle() + "\t\t" + dvds[i].getMovieYearOfRelease()  + "\t\t" + dvds[i].getMovieAgeClassification() + "\t\t" + dvds[i].getMovieGenre() + "\t" + dvds[i].getMoviePlayingTime());
    /// System.out.println("\n "+ dvd.toString());





    }

 /* Save all Book's in the array
  * to the text file
  */
    public void save(dvdClass[] dvds)
    {
        addPanel.setVisible(false);
        disPanel.setVisible(true);
        txtAreaPanel.setVisible(false);

    //  rdbSave.setEnabled(false);
    //  rdbAdd.setEnabled(false);


        for(int i=0;i<dvdz.length;i++)
            outputStream.println(dvdz[i]);


        outputStream.close();

        JOptionPane.showMessageDialog(null,"All Book's object in the array,\n has been save to text file");

    }

    /* Closing the GUI
     * terminate application
     */
    public void exit()
    {
        addPanel.setVisible(false);
        disPanel.setVisible(false);
        txtAreaPanel.setVisible(false);
        System.exit(0);
    }

    /** Clear any existing object in the array
     *  Load Book object in the from file
     *  Place them in the arry
     */

    /* send you back to main Panel
     */
    public void back()
    {
            disPanel.setVisible(true);
            txtAreaPanel.setVisible(false);
            addPanel.setVisible(false);
    }
    /* Add a new Book Object
     * atthe end of the array
     */
    public void addDvd(dvdClass[] dvd5)
    {
        if(validateM())
        {
            String t, a, g;
            int y,ti;


            t = txtMovieTitle.getText();
            a = txtAgeClassification.getText();
            g = txtMovieGenre.getText();

            t = t.replace(" ","");
            g = g.replace(" ","");
            a = a.replace(" ","");

            ti = Integer.parseInt(txtMovieTime.getText());
            y = Integer.parseInt(txtYearOfRelease.getText());


            dvdz[4]= new dvdClass(t,y,a,g,ti);
        //  dvd5 = new dvdClass();

//          dvdz = new dvdClass[] {dvd1, dvd2, dvd3,dvd4,dvd5};

            s += 1;

            txtMovieTitle.setText("");
            txtYearOfRelease.setText("");
            txtAgeClassification.setText("");
            txtMovieGenre.setText("");
            txtMovieTime.setText("");

            JOptionPane.showMessageDialog(null,"ADD \n" + t + " " + y + " " + a + " " + g + " " + y +" "+ti+ "\n has been added in the end of the array");

        }




    }

    public int getArrayIndex(dvdClass[] dvds)
    {
        dvdClass s;


        int i=0;
        int count=0;

        String fileName = "Bks.txt";
        Scanner fromFile = null;

        try
        {
            fromFile = new Scanner(new File(fileName));

        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error opening the file " + "fileName");
            System.exit(0);
        }

        while(fromFile.hasNext())
        {

            count++;
        }
            return i;
    }

    //Clear any existing objects in the array
    public void clearArray()
    {

        for(int i=0;i<dvds.length;i++)
            dvds[i] = null;
    }
    /* Valide text fields
     * if are empty or not
     * send back error message if are empty
     */
    public boolean validateM()
    {
        boolean bRet     = true;
        String strErrMsg = "";
        String strTitle = txtMovieTitle.getText();
        String strYear  = txtYearOfRelease.getText();
        String strAgeClass = txtAgeClassification.getText();
        String strGenre = txtMovieGenre.getText();
        String strTime  = txtMovieTime.getText();


        if(strTitle == null || strTitle.length() < 1 )
        {
            strErrMsg = "The movie title field connot be empty.";
            bRet   = false;
        }
        else if(strAgeClass == null || strAgeClass.length() < 1)
        {
            strErrMsg = "The age classification field connot be empty.";
            bRet   = false;
        }
        else if(strGenre == null || strGenre.length() < 1)
        {
            strErrMsg = "The genre field connot be empty.";
            bRet   = false;
        }
        else
        {
            try
            {
                int yearR = Integer.parseInt(strYear);

                try
                {
                    int mTime =Integer.parseInt(strTime);
                }
                catch(NumberFormatException ex)
                {
                        strErrMsg = "The time field only acceps digits";
                        bRet       = false;
                }

            }
            catch(NumberFormatException ex)
            {
                strErrMsg  = "The year field only accepts digits";
                bRet      = false;
            }
        }

        if(!bRet)
        JOptionPane.showMessageDialog(null,strErrMsg);



        return bRet;


    }
}



/////////////////////////////DVD CLASS//////



///////////////////////////// DVD CLASS //////

public class dvdClass implements Comparable
{
    private String movieTitle;
    private String movieAgeClassification;
    private String movieGenre;
    private int movieYearOfRelease;
    private int moviePlayingTime;


    public dvdClass()
    {
        movieTitle = "";
        movieAgeClassification = "";
        movieGenre = "";
        movieYearOfRelease = 0;
        moviePlayingTime = 0;
    }// end of default constructor

    public dvdClass(String title,int  year,String age,String genre, int time)
    {

        movieTitle = title;
        movieAgeClassification = age;
        movieGenre = genre;
        movieYearOfRelease = year;
        moviePlayingTime = time;
    }// end of constructor

    public String getMovieTitle()
    {
        return movieTitle;
    }
    public void setMovieTitle(String t)
    {
        movieTitle = t;
    }

    public int getMovieYearOfRelease()
    {
        return movieYearOfRelease;
    }
    public void setYearOfRelease(int y)
    {
        movieYearOfRelease = y;
    }

    public String getMovieAgeClassification()
    {
        return movieAgeClassification;
    }
    public void setMovieAgeClassification(String a)
    {
        movieAgeClassification  = a;
    }

    public String getMovieGenre()
    {
        return movieGenre;
    }
    public void setMovieGenre(String g)
    {
        movieGenre = g;
    }

    public int getMoviePlayingTime()
    {
        return moviePlayingTime;
    }

    //pt is the abbreviation of playing time
    public void setMoviePlayingTime(int pt)
    {
        moviePlayingTime = pt;
    }

    public String toString()
    {
        return movieTitle + "\t\t" + movieYearOfRelease + "\t\t" + movieAgeClassification + "\t\t" + movieGenre + "\t" + moviePlayingTime;
    }
    //end of toString method

    //display method

                public int compareTo(Object obj)
        {

            if (obj instanceof dvdClass)
            {

                dvdClass dvd = (dvdClass) obj;
                if (this.movieYearOfRelease < dvd.getMovieYearOfRelease())
                    return 1;
                else if (this.movieYearOfRelease > dvd.getMovieYearOfRelease())
                    return -1;
                    else

                    return(movieTitle.charAt(movieTitle.length() - 1) - movieTitle.charAt(movieTitle.length() - 1) );


            }
            return 0;
        }

    }

推荐答案

Use Array.binarSearch[^] to find the location for your insertion. Move items to the right of the insertion index, then insert your item. Here is a concise example[^] of the technique.
You may want to reserve some space at the back of the array for expansions to avoid copying every time you add an element.
Use Array.binarSearch[^] to find the location for your insertion. Move items to the right of the insertion index, then insert your item. Here is a concise example[^] of the technique.
You may want to reserve some space at the back of the array for expansions to avoid copying every time you add an element.


这篇关于如何手动将元素插入数组并对元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆