Please follow me here!

Sunday, June 9, 2013

JAVA Program: Entering Non-Duplicate Numbers to a Linked List

Hello, everyone. Gregory Desrosiers here. Today, what I'm going to present to you is the code for another JAVA program I did in one of my three JAVA courses I've taken. This is Exercise 22.2 of Daniel Liang's "Introduction to JAVA Programming" published by Pearson Education, Inc.


What I'm showing you is a simple Swing-based program where you enter numbers and you have the option to sort, shuffle, and reverse. This is done by entering the numbers you enter in a linked list and then when one of the three buttons are pressed, the appropriate method from the imported Collections class is executed. You can enter all real numbers into the text field, but you want to make sure you do not type in duplicates. You also want to be careful with entering something in the text field, because the list will not accept all strings.

Let me share with you what the program looks like, and then I'll show you the code for it. I have some photos to show it off how it works.

This is how you start off the program when you start running it  from the IDE
[integrated development environment] or through console commands.
You have three panels: the panel at the top where it says "Enter a number: " and a text field where you enter your number, whether it's an integer or a decimal, including 0; the center panel from which you can see the values you've entered (this is actually a text area); and the bottom panel with three interactive buttons. Each one will perform a different operation as you can see with the text over each button.

Let's say you want to put in 55. Type in "55" in the text field at the top, then press Enter.
You will now see  "55" in the text area. Let's add some values!
Here's what the program looks like with some values entered. Take note of the line
wrapping being done in the text area based on words and not characters.
The program does allow you to enter any values you want, except that you are not allowed to enter duplicates [those are values you've already entered once that you want to enter again.]. Watch what happens if you attempt to do so:

A dialog box, with the default Information icon, of course, is displayed in the center of
the screen, telling you that the value you're entering in your linked list already exists and
therefore the program will not add the value for you again.
To avoid being cubersome with the input, I have developed a method where for each entry you put in, it goes through a check to make sure it is a number. What I mean is, we do not want to add anything in our list that contains alpha characters or symbols other than numbers. It even handles decimals where you accidentally put in more than one decimal point!

You are entering a value that contains two decimal points. The program detects that it is not a valid number,
and therefore it will not be added to the linked list.
Here's another example of checking the input for foreign symbols:
Hyphens, minus signs, plus signs, forward slashes, asterisks, percent signs, hashes, ampersands,
exponent hats and the dollar sign are some of the illegal symbols the program searches for to declare
"this value is not safe for edition to the linked list."
What about the three buttons at the bottom of the main window? Let's go through each one of them in detail:
The "Sort" button sorts the values in the list in increasing order.
The "Shuffle" button mixes all the values randomly.
Finally, the "Reverse" button reverses the order of the values currently displayed; the photo
on top is the result of the photo before.
A few learning complaints about this program is, there is no maximum number of values you can enter. It's possible to get a list overload because of limited memory resources. Also, there is no "Remove" button, which would remove the last element in the current list. And there is no menu to change the display settings as well as to save and load data. Then again, this program is more of an experiment with data structures instead of making programs highly useful for the real world.

Here's the code for the program:


import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Chapter22Exercise2 extends JFrame
{
private static final long serialVersionUID = -3246039154138288054L;

private JPanel mainPanel;

// Top Panel Components
private JPanel topPanel;
private JLabel entryLabel;
private JTextField entryTextField;

// Middle Components
private JTextArea visibleTextArea;
private JScrollPane textAreaWithScrollPane;

// Bottom Panel Components
private JPanel bottomPanel;
private JButton sortButton;
private JButton shuffleButton;
private JButton reverseButton;

// Core Components
private static LinkedList<BigDecimal> numberList;
private static StringBuilder visibleString;
private static DecimalFormat numberFormatter;

public static void main(String[] args)
{
numberList = new LinkedList<BigDecimal>();
visibleString = new StringBuilder();
numberFormatter = new DecimalFormat("0.###############");

new Chapter22Exercise2();
}

public Chapter22Exercise2()
{
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(3, 0));

// Top Panel Construction
topPanel = new JPanel();

entryLabel = new JLabel("Enter a number:");
entryTextField = new JTextField(15);

entryTextField.addActionListener(new Listener());

topPanel.add(entryLabel);
topPanel.add(entryTextField);

mainPanel.add(topPanel, BorderLayout.NORTH);

// Middle Component Construction
visibleTextArea = new JTextArea(10, 40);
visibleTextArea.setWrapStyleWord(true);
visibleTextArea.setLineWrap(true);

textAreaWithScrollPane = new JScrollPane(visibleTextArea);
textAreaWithScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textAreaWithScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

mainPanel.add(textAreaWithScrollPane);

// Bottom Panel Construction
bottomPanel = new JPanel();

sortButton = new JButton("Sort");
shuffleButton = new JButton("Shuffle");
reverseButton = new JButton("Reverse");

sortButton.addActionListener(new Listener());
shuffleButton.addActionListener(new Listener());
reverseButton.addActionListener(new Listener());

bottomPanel.add(sortButton);
bottomPanel.add(shuffleButton);
bottomPanel.add(reverseButton);

mainPanel.add(bottomPanel, BorderLayout.SOUTH);

// Finalization

add(mainPanel);

setTitle("Exercise22_2");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}

  // This is how the buttons actually respond to your clicks.
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sortButton)
                        // This is what happens when you click the "Sort" button.
{
Collections.sort(numberList);

// We want to modify the StringBuilder object so that way  // the string to be displayed contains the new information.
if (visibleString.length() != 0)
{
visibleString.delete(0, visibleString.length());
}

for (int y = 0; y < numberList.size(); y++)
{
visibleString.append(numberFormatter.format(numberList.get(y)) + " ");
visibleTextArea.setText(visibleString.toString());
}
}
else if (e.getSource() == shuffleButton)
                        // This is what happens when you click the "Shuffle" button

{
Collections.shuffle(numberList);

if (visibleString.length() != 0)
{
visibleString.delete(0, visibleString.length());
}

for (int y = 0; y < numberList.size(); y++)
{
visibleString.append(numberFormatter.format(numberList.get(y)) + " ");
visibleTextArea.setText(visibleString.toString());
}
}
else if (e.getSource() == reverseButton)
                        // This is what happens when you click on the "Reverse" button.
{
Collections.reverse(numberList);

if (visibleString.length() != 0)
{
visibleString.delete(0, visibleString.length());
}

for (int y = 0; y < numberList.size(); y++)
{
visibleString.append(numberFormatter.format(numberList.get(y)) + " ");
visibleTextArea.setText(visibleString.toString());
}
}
else if (e.getSource() == entryTextField)
                        // This is what happens when you press Enter upon typing a value in 
                        // the entry text field.
{
String stringEntered = entryTextField.getText();

if (!stringIsNumber(stringEntered))
JOptionPane.showMessageDialog(null, "The string you've entered is not a number and therefore will not be added to the list.", "Not a number", JOptionPane.ERROR_MESSAGE);
else
{
if (!numberList.contains(new BigDecimal(stringEntered)))
numberList.add(new BigDecimal(stringEntered));
else
JOptionPane.showMessageDialog(null, "The element you're asking the program to add already exists.\nDuplicates are not allowed.", "Element Already Exists", JOptionPane.INFORMATION_MESSAGE);

if (visibleString.length() != 0)
{
visibleString.delete(0, visibleString.length());
}

for (int y = 0; y < numberList.size(); y++)
{
visibleString.append(numberFormatter.format(numberList.get(y)) + " ");
visibleTextArea.setText(visibleString.toString());
}
}
}
}

// This method checks to see whether what you're entering is actually a 
// number.
private boolean stringIsNumber(String s)
{
boolean stringIsNumber = true;
byte numberOfNegativeSigns = 0;
byte numberOfDigits = 0;
byte numberOfDecimalPoints = 0;

for (int x = 0; x < s.length(); x++)
{
if (s.charAt(x) == '-')
numberOfNegativeSigns++;
else if (Character.isDigit(s.charAt(x)))
numberOfDigits++;
else if (s.charAt(x) == '.')
numberOfDecimalPoints++;
else
stringIsNumber = false;
}

if (numberOfNegativeSigns > 1 || numberOfDigits == 0 || numberOfDecimalPoints > 1)
stringIsNumber = false;

return stringIsNumber;
}
}
}


Well, that does it for this program, all right?

Follow me through the following pages and be sure to like my e-book page on Facebook for support!!

E-book: https://www.facebook.com/TheAspergerComputerGregDes

Facebook: https://www.facebook.com/pages/Gregory-Desrosiers/171954446270382?ref=hl
Twitter: http://www.twitter.com/GregoryDes
Google+: Search up "Gregory Desrosiers" in the Search Engine, then click on the profile that has a photo of me with two thumbs up.
YouTube: http://www.youtube.com/user/Bammer2001

Have a great time, and I'll see you later!!

Google+ Followers

Popular Posts by Gregory