0

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

While pursuing a Computer Science degree, I founded DaniWeb.com, an online community for developers and IT professionals. I coded the backend platform from the ground up and I also do all of the advertising sales and SEO. I'm a super-geeky programmer with a passion for Internet marketing.

2
Contributors
1
Reply
2
Views
12 Years
Discussion Span
Last Post by Ghost
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.