RobustInput

cscgal cscgal is offline Offline Sep 20th, 2004, 11:24 am |
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.
Quick reply to this message  
Java Syntax
  1. package robustinput;
  2. import javax.swing.JScrollPane;
  3. import javax.swing.JOptionPane;
  4. import javax.swing.JTextArea;
  5. import java.text.DecimalFormat;
  6. public class RobustInput
  7. {
  8. public static void main(String args[])
  9. {
  10. int inum = 0;
  11. String typeErr = "That is not an integer.";
  12. String rangeErr = "That number is out of range.";
  13. boolean badType;
  14. boolean badRange;
  15. do
  16. {
  17. badType = false;
  18. badRange = false;
  19. try
  20. {
  21. inum = Integer.parseInt(JOptionPane.showInputDialog(null,
  22. "Enter Positive Integer"));
  23. }
  24. catch (NumberFormatException e)
  25. {
  26. badType = true;
  27. inum = 1;
  28. }
  29. if ((inum < 1) || (inum > 150)) badRange = true;
  30. if (badType) JOptionPane.showMessageDialog(null, typeErr,
  31. "Invalid",JOptionPane.ERROR_MESSAGE);
  32. if (badRange) JOptionPane.showMessageDialog(null, rangeErr,
  33. "Invalid",JOptionPane.ERROR_MESSAGE);
  34. } while (badType || badRange);
  35. System.out.println("\n\n\tYou entered: " + inum);
  36. JTextArea outputArea = new JTextArea();
  37. outputArea.append(" i\t Sqrt(i) \n_____________________\n");
  38. DecimalFormat dec4 = new DecimalFormat("0.0000");
  39. for (int i = 1; i <= inum; i++)
  40. {
  41. outputArea.append("\n ");
  42. if (i < 10) outputArea.append("00");
  43. else if (i < 100) outputArea.append("0");
  44. outputArea.append(i + "\t");
  45. if (i < 100) outputArea.append("0");
  46. outputArea.append(dec4.format(Math.sqrt((double)i)));
  47. }
  48. // JOptionPane.showMessageDialog(null, outputArea, "Square Root Table",
  49. JOptionPane.INFORMATION_MESSAGE);
  50. JScrollPane scroller = new JScrollPane(outputArea);
  51. JOptionPane.showMessageDialog(null, scroller, "Square Root Table",
  52. JOptionPane.INFORMATION_MESSAGE);
  53. }
  54. }
0
Ghost Ghost is offline Offline | Oct 3rd, 2004
nice code - can u explain it more?
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC