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);
}
}