RobustInput

Updated Dani 0 Tallied Votes 225 Views Share

A single class consisting of multiple methods is used to demonstrate the robustness of keyboard input in Java. A try-catch block is used. The program graphically prints out a square root table by using JTextArea, JScrollPane and JOptionPane.

package robustinput;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.text.DecimalFormat;
public class RobustInput
{
    public static void main(String args[])
    {
        int inum = 0;
        String typeErr = "That is not an integer.";
        String rangeErr = "That number is out of range.";
        boolean badType;
        boolean badRange;
        do
        {
            badType = false;
            badRange = false;
            try
            {
                inum = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Enter Positive Integer"));
            }
            catch (NumberFormatException e)
            {
                badType = true;
                inum = 1;
            }
            if ((inum < 1) || (inum > 150)) badRange = true;
            if (badType) JOptionPane.showMessageDialog(null, typeErr,
            "Invalid",JOptionPane.ERROR_MESSAGE);
            if (badRange) JOptionPane.showMessageDialog(null, rangeErr,
            "Invalid",JOptionPane.ERROR_MESSAGE);
        } while (badType || badRange);
        System.out.println("\n\n\tYou entered: " + inum);
        JTextArea outputArea = new JTextArea();
        outputArea.append(" i\t Sqrt(i) \n_____________________\n");
        DecimalFormat dec4 = new DecimalFormat("0.0000");
        for (int i = 1; i <= inum; i++)
        {
            outputArea.append("\n ");
            if (i < 10) outputArea.append("00");
            else if (i < 100) outputArea.append("0");
            outputArea.append(i + "\t");
            if (i < 100) outputArea.append("0");
            outputArea.append(dec4.format(Math.sqrt((double)i)));
        }
        // JOptionPane.showMessageDialog(null, outputArea, "Square Root Table",
        JOptionPane.INFORMATION_MESSAGE);
        JScrollPane scroller = new JScrollPane(outputArea);
        JOptionPane.showMessageDialog(null, scroller, "Square Root Table",
        JOptionPane.INFORMATION_MESSAGE);
    }
}
Ghost 0 Posting Whiz

nice code - can u explain it more?

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.