8 Replies Latest reply: Feb 14, 2007 5:40 AM by 807606 RSS

    Array Problem Help - Comparing 5 values

    807606
      Sadly I'm not new to Java but still quite bad at it. I've got a Java How to Program Textbook and I've read it a few times and even got a Student Solutions manual to see if I could learn more from actual solutions.

      Anyway I'm currently working through arrays and learning bits and pieces but I still can't accomplish most of the excercises and this is my current cunundrum.

      Write an applet that uses a one dimensional array that inputs 5 numbers that are between 10 and 100 inclusive. As each number is read display it only if it is not different to any number already read. Provide for the worst case in which all 5 numbers are displayed. The smallest possible array should be used and the result displayed in a JTextArea and it should also use setText after each value has been inputed.
      import javax.swing.*;
      import java.awt.*;
      import java.awt.event.*;
      
      public class Input extends JApplet implements ActionListener {
           JTextArea outputArea;
           JLabel label;
           JTextField inputField;
           int numbers[];
      
      public void init()
           {
                
           numbers = new int[5];
           
           outputArea = new JTextArea();
           inputField = new JTextField(10);
           inputField.addActionListener(this);
           label = new JLabel("Please Enter a number between 10 and 100");
           
           
           Container container = getContentPane();
           container.setLayout(new FlowLayout());
           container.add(inputField);
           container.add(label);
           container.add(outputArea);
                
           }
           
           
           public void actionPerformed(ActionEvent actionevent)
           {     
           
                int number = Integer.parseInt(inputField.getText());
                
                for(int counter = 0; counter < numbers.length; counter++)
                {
                     
                }
           
                     
                     
              } 
      } 
      Ok so that's not all I've done. I have tried a few things but I just ended up deleting it because it couldn't accomplish what I had it set out to do. Mostly I didn't know how to make it into a loop that would stop after five numbers were read or how to compare the already entered values to the other array values. Also I couldn't understand how to set the text without deleting the text that was already displayed. Just a little advice in the right direction I would greatly appreciate.
        • 1. Re: Array Problem Help - Comparing 5 values
          807606
          Any help at all?
          • 2. Re: Array Problem Help - Comparing 5 values
            807606
            I'm not sure what your trying to do. Do you want an array with 5 unique numbers or an array with any 5 numbers and only display the unique ones?

            Either way I'd suggest another variable that keeps track of how many values are stored in the array. This will make looping more efficient. When the array is empty don't loop at all instead of 5 times like you have now. Another thing you will need to check for is if the array is full. If the user enters a sixth number then where do you insert it? Depending on your code you might get an ArrayIndexOutOfBoundsException.
            • 3. Re: Array Problem Help - Comparing 5 values
              807606
              Yeh well I guess basically what I am asking is the user inputs 5 numbers and they're only displayed if if they are unique and they are displayed on an action event each time. So setText would be used to update the text field.

              So I was thinking it would have to be something like:
              int[0] = Integer.parseInt(inputField.getText());
              
              if (int[0] != int[1] && int[2] && int [3] && int [4]);
              output += (int[0] +"\n");
              setText.OutputArea(output); 
              
              inputField.setText("");
              And so on for all the inputs however I can't figure out how you're supposed to coerce input from the user before it sets the text at null and then get's the text at null.

              I'd also like to know how to make sure the applet finishes when the array reaches it's array.length.

              I guess the solution to appending output would just to append it after each if statement.... hmmm maybe I can do this now.

              Message was edited by:
              Outsider
              • 4. Re: Array Problem Help - Comparing 5 values
                807606
                here is some very rough code that does kinda what you want. its not an applet, but its all the same really.
                import javax.swing.*;
                import java.awt.event.*;
                import java.awt.*;
                
                public class Input {
                    static JTextArea outputArea;
                    static JLabel label;
                    static JTextField inputField;
                    static int numbers[];
                    static int count;
                
                    public static void main(String[] args) {
                        numbers = new int[5];
                        count = 0;
                        outputArea = new JTextArea();
                        inputField = new JFormattedTextField();
                        label = new JLabel("Please Enter a number between 10 and 100");
                
                
                        JFrame frame = new JFrame();
                        frame.getContentPane().add(inputField, BorderLayout.NORTH);
                        frame.getContentPane().add(outputArea, BorderLayout.SOUTH);
                        frame.pack();
                        frame.setVisible(true);
                
                        inputField.addKeyListener(new KeyListener() {
                            public void keyTyped(KeyEvent e) { }
                            public void keyPressed(KeyEvent e) { }
                
                            public void keyReleased(KeyEvent e) {
                                try {
                                    int input = Integer.parseInt(inputField.getText());
                
                                    // is number in range?
                                    if (input >= 10 && input <= 100) {
                
                                        // has number already been entered?
                                        for (int number : numbers) {
                                            if (number == input)
                                                throw new Exception("That number has been entered already");
                                        }
                
                                        numbers[count] = input;
                                        outputArea.setText("" + numbers[count]);
                                        count++;
                                    } else
                                        throw new Exception("Please enter a value between 10 and 100");
                                } catch (ArrayIndexOutOfBoundsException ex) {
                                    outputArea.setText("You have already entered 5 numbers");
                                } catch(Exception ex1) {
                                    outputArea.setText("Error: " + ex1.getMessage());
                                }
                            }
                        });
                    }
                }
                • 5. Re: Array Problem Help - Comparing 5 values
                  807606
                  Mostly I didn't know how to make it into a loop that would stop after five numbers were read or how to compare the already entered values to the other array values

                  Suggestion: use a String to check for matching values. Add them in as you check. and only perform the task if it succeeds:
                  semi-peudocode
                  if (myString.indexOf( n ) == -1){
                  /*the task
                  ...
                  String += n;
                  }
                  My professor has a thing for flexibility. This way you won't ever have to go an re-type if he changes it to checking for 20 number etc...
                  • 6. Re: Array Problem Help - Comparing 5 values
                    807606
                    Thanks for the help guys. Unfortunately most of that is beyond the scope of the chapter so I can't really use it.. It'll just have to be an enormous if... else with 5 inputs I guess.
                    • 7. Re: Array Problem Help - Comparing 5 values
                      807606
                      No enormous if.

                      Write another method that returns a boolean and takes the value to be inserted as a parameter. Then loop over the array. If you find the value already in the array return true. If the loop exits return false. Then in your other method do this:
                      if(! findNumber(value)) {
                          insert number into array
                      } else {
                          print message that number has already been entered.
                      }
                      • 8. Re: Array Problem Help - Comparing 5 values
                        807606
                        Ahhhhhh. I see now. Still how would I get the array to tick over based on the input? Should I just have five JTextFields and have events for all of them?