0

I'm gonna be honest, I've been working on an assignment and I am BEYOND stuck. I'm creating a simple java applet that lets the user input 10 numbers. the program sanitizes that input, making sure only a number is entered, and that the number must be between 0 and 9.

so far no problems. used given examples, searched the web for proper syntax and logic. my code compiles without complaining. however once i try my first number, as long as its valid input, my program just ups and tells me the number i just entered is the largest, and doesn't wait for to enter 10 numbers.

My guess is that i have half an applet program, and I'm not outputting right, or something in my loop is wrong, but the logic seems good.

almost forgot to mention. i don't know how to make output text in the applet, any help with that would be awesome, but its not my primary concern.

my current code:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.JOptionPane;

public class largest extends Applet implements ActionListener{
private static final long serialVersionUID = 1L;


//Create components for Applet
Label numberLabel = new Label("Enter a number:");
TextField numberField = new TextField(10);  // Sets the size of the text field, You still may type as much data into the field that you want, input will need to be sanitized later

Label topNumberLabel = new Label("The top number is:");
Button calcButton = new Button("Ok");
public void init()
{
    // Add controls to the applet window
    add(numberLabel);
    add(numberField);
    add(topNumberLabel);
    add(calcButton);
    calcButton.addActionListener(this);
    setSize(300, 200);  // Sets the size of the applet window
}

public void actionPerformed(ActionEvent e) {
    // Variables for counting, user input, and storage for largest number
    double counter = 0;
    double number = 0;
    double largest = 0;

    // Allows user to input 10 times
    while (counter<10)
    {
        try { //Sanitize user input, make sure input entered is a number
            number = Double.parseDouble(numberField.getText());
        } catch (NumberFormatException ex) {
            numberField.requestFocus();
            JOptionPane.showMessageDialog(null, "Input invalid, please enter an integer",
                    "///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (number < 0 || number > 9) { //Sanitize user input, make sure the given number is between 0 and 9
            numberField.requestFocus();
            JOptionPane.showMessageDialog(null,
                    "The number entered must be between 0 and 9",
                    "///-D-A-T-A---E-R-R-O-R-\\\\\\", JOptionPane.ERROR_MESSAGE);
            return;
        }
        counter++;

    // Determine what the largest number entered is by comparing to a baseline
    // of previous numbers or zero if just beginning loop
    if (number > largest)largest=number;

    }

        // Display's the largest number that got entered by user
        JOptionPane.showMessageDialog(null," The largest number entered was " + largest);
    }

}

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    You just read the same number 10 times. When the button is clicked your `actionPerformed` method runs and loops 10 times reading the same number. I would also suggest that you don't extend `ActionListener` in your `Applet` class - this breaks OO. You should use an anonymous class. Also you may want to read [this](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). Pay special attention to the "no one uses AWT anymore" section... – Boris the Spider Sep 22 '13 at 09:55
  • 1
    Your problem is that your `while` loop is inside your `actionPerformed` method. So you just loop over and over, for just one single action. Once you've looped 10 times, of course, your loop exits and shows its result. Think about how to do this _without_ the loop. – Dawood ibn Kareem Sep 22 '13 at 09:57
  • i have to use a loop. part of the assignment. my original solution was to due this using an array and just loop through an array, but had throw it out. – Fustrated Syntax Sep 22 '13 at 10:35
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Sep 22 '13 at 10:49
  • I totally agree that applets are overcomplicated, however my textbook is chock full of the stuff. our assignments aren't always designed JUST for applets, but not much else to code with if my examples are applet based. – Fustrated Syntax Sep 22 '13 at 10:57

2 Answers2

0

It is because this line

number = Double.parseDouble(numberField.getText());

is done 10 times as soon as you've entered a number in the field, you wouldn't get the time to change the number in the field before the loop is finished.

Magnus
  • 379
  • 1
  • 15
0

You are looping the 10 times as expected, but each time you are just getting the field's value with getText(). This doesn't wait for the user to change the number, so all 10 of the numbers are the same. You must define counter and largest as fields, and change each time actionPerformed is called. Here's code:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.JOptionPane;

public class largest extends Applet implements ActionListener{
    private static final long serialVersionUID = 1L;

    private int counter = 0; // These are the variables
    private double largest = 0; // from actionPerformed().

    // ...

    public void actionPerformed(ActionEvent e) {
        // Variable for user input
        double number = 0;

        try { //Sanitize user input, make sure input entered is a number
            number = Double.parseDouble(numberField.getText());
        } catch (NumberFormatException ex) {
            numberField.requestFocus();
            JOptionPane.showMessageDialog(null,
                    "Input invalid, please enter an integer",
                    "///-D-A-T-A---E-R-R-O-R-\\\\\\",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (number < 0 || number > 9) { //Sanitize user input, make sure the given number is between 0 and 9
            numberField.requestFocus();
            JOptionPane.showMessageDialog(null,
                    "The number entered must be between 0 and 9",
                    "///-D-A-T-A---E-R-R-O-R-\\\\\\",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        counter++;
        // Determine what the largest number entered is by comparing to a baseline
        // of previous numbers or zero if just beginning loop
        if (number > largest)largest=number;
        // Allows user to input 10 times
        if (counter==10)
        {
            // Display's the largest number that got entered by user
            JOptionPane.showMessageDialog(null,
                    "The largest number entered was " + largest);
        }
    }
}
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
  • mm, double and int conversion error. made my variables double. the code you added makes it so that it tells me the first number i enter is the largest, and lets me input numbers infinitely after that. gonna go and make counter and largest fields like you said – Fustrated Syntax Sep 22 '13 at 10:32
  • @FustratedSyntax OK, fixed that, just make `largest` a `double` :) However, `counter` should still be an `int`, consumes less memory and no rounding errors. – PurkkaKoodari Sep 22 '13 at 10:48
  • ok. honestly im a noob at this, how do i make largest and number fields? the code you added doesn't allow me to keep adding numbers :/ – Fustrated Syntax Sep 22 '13 at 10:52
  • @FustratedSyntax To make the fields put them inside the class, but not inside any method (see my code there, they're after `serialVersionUID`). And to make it continue accepting numbers after the 10th one and every time after the 10th show the largest, just replace `if (counter==10)` with `if (counter>=10)`. – PurkkaKoodari Sep 22 '13 at 10:57
  • oh, ok, so i already did that then. but your code doesn't work. i can't enter 10 numbers at all. only one and then i get the your largest number was the first one, then i can enter infinitely. i don't want it to continue accepting numbers, that's actually the error I'm experiencing :C. it needs to let me enter 10 then tell me highest, then terminate (adding terminating code will be easy) – Fustrated Syntax Sep 22 '13 at 11:00
  • @FustratedSyntax Well, did you replace your `actionPerformed` with mine? – PurkkaKoodari Sep 22 '13 at 11:06
  • if you mean the code if (counter==10) and so on, yea. i dont see any other differences in that area of code. – Fustrated Syntax Sep 22 '13 at 11:15
  • alright i did a direct overwrite with your code, i can't find whats different about it but it worked. still need to display a counter in the applet. thanks for the great help so far XD – Fustrated Syntax Sep 22 '13 at 11:19
  • YUSH, figured the difference, lol so simple. removed the while syntax. thats what was killing me. THANKS SO MUCH – Fustrated Syntax Sep 22 '13 at 11:21