| | |
RobustInput
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); } }
| Thread Tools | Search this Thread |
911 actionlistener addressbook android api append applet application array arrays automation binary block bluetooth character class client code component consumer csv database desktop developmenthelp eclipse error fractal ftp game gameprogramming givemetehcodez graphics gui html ide image integer j2me j2seprojects japplet java javaarraylist javac javaee javaprojects jni jpanel julia lego linked linux list loops mac map method methods mobile netbeans newbie number objects online oriented panel printf problem program programming project projects properties recursion replaydirector reporting researchinmotion rotatetext rsa scanner se server set singleton sms sort sql string swing system test textfields threads time title tree tutorial-sample ubuntu update windows working



