Hi! Haven't posted on danniweb for awhile, but I'm hoping I can get some help. I am in the middle of learning Java, which will be my second language after python, and I have come across a problem, ordering a list of integers in an array.

In python, there's a simple order function that will organize a list by integer or character code (effectively alphabatizing a list of strings, provided they all start with the same case), but as far as I can tell, there's no method in the java API to order an array of ints.

This is what I have so far, it is part of a larger program, a timer that will keep track of the top five longest times recorded. TextIO is an external class written by David Eck, author of one of the books I am teaching myself from. There are several errors with this current version, with some things changing to seemingly arbitrary numbers. The other big thing, more evident in the rest of the program, is that I believe I have violated a good deal of good practice and coding conventions.

public static void recordUpdate(int spoken){
        int[] tempArray = new int[5];
        TextIO.readFile("records.txt");
        
        
        for(int i = 0; i < 5; i++){

            tempArray[i] = TextIO.getlnInt();
        }// end for
        for(int i = 0; i < 5; i++){
            if (spoken >= tempArray[i]){ //if new number is greater than a number in the records
                for(int j = 0; j < (tempArray.length - i - 1); j++){
                tempArray[j] = tempArray[j + 1];
                }//end for
                tempArray[i] = spoken;
                break;
            }//end if
            /*if (i == tempArray[i-1]){
                break;}
not sure where I was going here, left it for a day forgot to comment it, came back to it and couldn't remember my point. Was something to do with one of the for loops needing to break to avoid something screwy.
           */
        
        }//end for
        GUITimer.records = tempArray.clone(); //copies the temporary array into the variable used by the rest of hte program
        for(int i = 0; i < 5; i++){
            TextIO.putln(GUITimer.records[i]);
        }//end for
    }

The code is supposed to go through the array, then stop if it finds a number less then the value the clock was stopped at. Then it attempts to 'bump' everything in the array from that point forward down a spot, then finnally override the stopping spot with the new value. I haven't found a way to get rid of the last integer in the array.

My friend and I have been puzzling over this problem for awhile, so any help on how to create a for loop to order integers would be appreciated. Code for the rest of the program follows, keep in mind that the timer is not very accurate, but it's accurate enough for it's purposes.

edit: code has had a few in-joke variables changed for clarity while posting, so there may have been some accidental errors that aren't normally in the program. Remember you will need the TextIO class for it to compile and run correctly.

import java.awt.*;
import java.awt.event.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class GUITimer
{
    static boolean isRecording = true;
    static int timeSpoken = 0;
    static final boolean moreMagic = true;
    static int[] records = new int[5];
    public static void main(String[] args)
    {
        CenteredFrame frame = new CenteredFrame();
        
        //TextIO.readFile("records.txt");
        recordUpdate( timeSpoken );
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        if (moreMagic){
        frame.show();
        }
    }
    
    public static void recordUpdate(int spoken){
        int[] tempArray = new int[5];
        TextIO.readFile("records.txt");
        
        
        for(int i = 0; i < 5; i++){

            tempArray[i] = TextIO.getlnInt();
        }// end for
        for(int i = 0; i < 5; i++){
            if (spoken >= tempArray[i]){ //if new number is greater than a number
                for(int j = 0; j < (tempArray.length - i - 1); j++){
                tempArray[j] = tempArray[j + 1];
                }//end for
                tempArray[i] = spoken;
                break;
            }//end if
/*
            if (i == tempArray[i-1]){
                break;}
*/
        
        }//end for
        GUITimer.records = tempArray.clone();
        for(int i = 0; i < 5; i++){
            TextIO.putln(GUITimer.records[i]);
        }//end for
    }
    
}

class CenteredFrame extends JFrame
{
    public CenteredFrame()
    {
        setTitle("Timer of sorts");
        
        // get screen dimensions
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
        int screenHeight = screenSize.height;
        int screenWidth = screenSize.width;
        
        // center frame in screen
        setSize(screenWidth / 2, screenHeight / 2);
        setLocation(screenWidth / 4, screenHeight / 4);

        PanelStuff panel = new PanelStuff();
        Container contentPane = getContentPane();
        contentPane.add(panel);
    }
}

class PanelStuff extends JPanel
{
    static int seconds = 0;
    static int minutes = 0;
    static int hours = 0;
    static int timeTemp = 0;
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        
        String secondsString = Integer.toString(seconds);
        String minutesString = Integer.toString(minutes);
        String hoursString = Integer.toString((hours));
        
        if (seconds < 10)
        {
            secondsString = "0" + secondsString;
        }
        if (minutes < 10)
        {
            minutesString = "0" + minutesString;
        }
        if (hours < 10)
        {
            hoursString = "0" + hoursString;
        }
        
        
        String timeOutput = (hoursString + ":" + minutesString + ":" + secondsString);
        
        // The string properties
        g.setColor(new Color(250, 80, 0));
        String message = timeOutput;
        Font f = new Font("Serif", Font.BOLD, 36);
        g2.setFont(f);
        
        // measure the size of the message
        FontRenderContext context = g2.getFontRenderContext();
        Rectangle2D bounds = f.getStringBounds(message, context);
        
        // set (x,y) = top left corner of text
        double x = (getWidth() - bounds.getWidth()) /2;
        double y = (getHeight() - bounds.getHeight())/2;
        
        //add ascent to y to reach the baseline
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        g.drawString(message, (int)x, (int)baseY);
        
        // temp record test
        f = new Font("Serif", Font.BOLD, 15);
        g2.setFont(f);
        g.drawString(Integer.toString(GUITimer.records[0]) +
                Integer.toString(GUITimer.records[1]) +
                Integer.toString(GUITimer.records[2]) +
                Integer.toString(GUITimer.records[3]) +
                Integer.toString(GUITimer.records[4]), 50, 50);
        repaint();

    }
    public static void Convert()
    {
        timeTemp = GUITimer.timeSpoken;
            minutes = timeTemp / 60;
            seconds = timeTemp % 60;
        {
            hours = minutes / 60;
            minutes = minutes % 60;
        }
            
    }
    
    class CounterAction implements ActionListener{
        public void actionPerformed(ActionEvent evt){
            if (GUITimer.isRecording == true){
                GUITimer.timeSpoken = GUITimer.timeSpoken + 1;
                Convert();
            }
            else
                return;
        }
    }
    PanelStuff(){
        //DAN was here
        ActionListener listener = new CounterAction();
        Timer timer = new Timer(1000, listener);
        timer.start();
        
        JButton startBtn = new JButton("Start/Stop");
        JButton resetBtn = new JButton("Reset");
        
        add(startBtn);
        add(resetBtn);
        
        ButtonActionStart startAction = new ButtonActionStart();
        ButtonActionReset resetAction = new ButtonActionReset();
        
        startBtn.addActionListener(startAction);
        resetBtn.addActionListener(resetAction);
    }
    
    // button stuff
    private class ButtonActionStart implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {
            if (GUITimer.isRecording == false)
                GUITimer.isRecording = true;
            else
                GUITimer.isRecording = false;
        }
    }
    private class ButtonActionReset implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {
            TextIO.readFile("records.txt");
            GUITimer.recordUpdate(GUITimer.timeSpoken);
            
            GUITimer.timeSpoken = 0;
        }
        }
            
        }

Use class Arrays. This class contains various methods for manipulating arrays.

Info from API on sort(int[] a)

Here is a nice refference to sorting

An here is just small quick example

import java.util.*;

public class Sort {
    public static void main(String[] args) {
    	int[] arr = new int[] {5, 3, 1, 6, 7};
		Arrays.sort(arr);
		for(int i =0; i< arr.length; i++)
		{
			System.out.print(arr[i] + " ");
		}
		System.out.println();
    }
}

Instead of looping over the entire array to display it's contents, a clever way would be to convert it to a list and display it using it's toString() method (called implicitly). System.out.println(Arrays.asList(myArray));

Thank you very much, I was hoping there was something the API I was missing! :)

And remember that Python lists are NOT arrays.
Lists in Java also can be easily sorted (if there's an ordering defined for the content of course).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.