IT206 Lect 04 Java Programming PDF

Document Details

ThrilledIridium

Uploaded by ThrilledIridium

Minia University

Prof. Moheb Ramzy Girgis

Tags

Java programming input/output dialog boxes programming

Summary

This document is a lecture on Java programming, focusing on input/output and confirmation dialog boxes. The document provides examples and explanations about these concepts, useful to those starting to learn Java programming.

Full Transcript

Java Programming 4. I/O and Confirmation Dialog Boxes Java Programming 4. I/O and Confirmation Dialog Boxes Prof. Moheb Ramzy Girgis Department of Computer Science Faculty of Science...

Java Programming 4. I/O and Confirmation Dialog Boxes Java Programming 4. I/O and Confirmation Dialog Boxes Prof. Moheb Ramzy Girgis Department of Computer Science Faculty of Science Minia University Displaying Text in a Message Dialog Box The program in Listing 1.1 displays the text on the console. You can rewrite the program to display the text in a message dialog box. To do so, you need to use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system that you can reuse rather than “reinventing the wheel.” You can use the showMessageDialog method to display any text in a message dialog box, as shown below. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 1/13 Java Programming 4. I/O and Confirmation Dialog Boxes Displaying Text in a Message Dialog Box The new program is as follows: This program uses a Java class JOptionPane (line 9). Java’s predefined classes are grouped into packages. JOptionPane is in the javax.swing package. JOptionPane is imported to the program using the import statement in line 4 so that the compiler can locate the class without the full name javax.swing.JOptionPane. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Displaying Text in a Message Dialog Box The showMessageDialog method is a static method. Such a method should be invoked by using the class name followed by a dot operator (.) and the method name with arguments. There are several ways to use the showMessageDialog method. Here we will see only two ways. One is to use a statement, as shown in the example: JOptionPane.showMessageDialog(null, x); where x is a string for the text to be displayed. The first argument can always be null. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 2/13 Java Programming 4. I/O and Confirmation Dialog Boxes Displaying Text in a Message Dialog Box The other is to use a statement like this one: JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE); where x is a string for the text to be displayed, and y is a string for the title of the message box. The fourth argument can be JOptionPane.INFORMATION_MESSAGE, which causes the icon ( ) to be displayed in the message box, as shown in the following example. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Getting Input from Input Dialogs You can obtain input from the console. Alternatively, you may obtain input from an input dialog box by invoking the JOptionPane.showInputDialog method, as shown below: There are several ways to use the showInputDialog method. Here we will know only two ways to invoke it. One is to use a statement like this one: JOptionPane.showInputDialog(x); where x is a string for the prompting message. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 3/13 Java Programming 4. I/O and Confirmation Dialog Boxes Getting Input from Input Dialogs The other is to use a statement such as the following: String string = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE); where x is a string for the prompting message and y is a string for the title of the input dialog box, as shown in the example below. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Converting Strings to Numbers The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”. To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 4/13 Java Programming 4. I/O and Confirmation Dialog Boxes Problem: Computing Loan Payments The problem is to write a program that computes loan payments. The loan can be a car loan, a student loan, or a home mortgage loan. The program lets the user enter the interest rate, number of years, and loan amount, and displays the monthly and total payments. The formula to compute the monthly payment is as follows: The pow(a, b) method in the Math class can be used to compute ab. The Math class, which comes with the Java API, is available to all Java programs. For example, System.out.println(Math.pow(2, 3)); // Display 8.0 System.out.println(Math.pow(4, 0.5)); // Display 2.0 Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Problem: Computing Loan Payments The term can be computed using Math.pow(1 + monthlyInterestRate, numberOfYears * 12). The steps of developing the program: 1. Prompt the user to enter the annual interest rate, number of years, and loan amount. 2. Obtain the monthly interest rate from the annual interest rate. 3. Compute the monthly payment using the preceding formula. 4. Compute the total payment, which is the monthly payment multiplied by 12 and multiplied by the number of years. 5. Display the monthly payment and total payment. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 5/13 Java Programming 4. I/O and Confirmation Dialog Boxes Problem: Computing Loan Payments import javax.swing.JOptionPane; public class ComputeLoan { ComputeLoan.java public static void main(String[] args) { // Enter yearly interest rate String annualInterestRateString = JOptionPane.showInputDialog( "Enter yearly interest rate, for example 8.25:"); // Convert string to double double annualInterestRate = Double.parseDouble(annualInterestRateString); // Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200; // Enter number of years String numberOfYearsString = JOptionPane.showInputDialog( "Enter number of years as an integer, \nfor example 5:"); // Convert string to int int numberOfYears = Integer.parseInt(numberOfYearsString); Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Problem: Computing Loan Payments // Enter loan amount String loanString = JOptionPane.showInputDialog( "Enter loan amount, for example 120000.95:"); // Convert string to double double loanAmount = Double.parseDouble(loanString); // Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12; // Format to keep two digits after the decimal point monthlyPayment = (int)(monthlyPayment * 100) / 100.0; totalPayment = (int)(totalPayment * 100) / 100.0; // Display results String output = "The monthly payment is " + monthlyPayment + "\nThe total payment is " + totalPayment; JOptionPane.showMessageDialog(null,output ); Java Programming - Prof. Moheb Ramzy Girgis } Dept. of Computer Science - Faculty of Science  } Minia University 6/13 Java Programming 4. I/O and Confirmation Dialog Boxes Problem: Computing Loan Payments A sample run of the program The program accepts the annual interest rate (a), number of years (b), and loan amount (c), then displays the monthly payment and total payment (d). Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Converting Console I/O to Dialog Boxes Brief summary to aid in converting console I/O to dialog boxes Imports Console import java.util.*; // For Scanner class. Dialog import javax.swing.*; // For JOptionPane class. Initialization Console Scanner input = new Scanner(System.in); Dialog None required. Output Console System.out.println("Display this"); Dialog JOptionPane.showMessageDialog(null, "Display this"); Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 7/13 Java Programming 4. I/O and Confirmation Dialog Boxes Converting Console I/O to Dialog Boxes Line of text input String name; Console System.out.print("Enter your name: "); name = input.nextLine(); String name; Dialog name = JOptionPane.showInputDialog(null, "Enter your name"); Integer input System.out.print("Enter your age: "); Console int age = input.nextInt(); String aStr = JOptionPane.showInputDialog(null, "Enter your age"); int age = Integer.parseInt(aStr); Dialog Or these could be combined on one line, eliminating the temporary variable: int age = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter your age")); Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Example program written in two ways // Average3Scanner.java // Average three ints. Use Scanner. import java.util.Scanner; public class Average3Scanner { public static void main(String[] args) { int a, b, c, average; //... Initialize Scanner to read from console. Scanner input = new Scanner(System.in); //... Read three numbers from the console. System.out.print("Enter first number : "); a = input.nextInt(); System.out.print("Enter second number: "); b = input.nextInt(); System.out.print("Enter last number : "); c = input.nextInt(); //... Compute their average. average = (a + b + c) / 3; //... Display their average on the console. System.out.println("Average is " + average); Java Programming - Prof. Moheb Ramzy Girgis } Dept. of Computer Science - Faculty of Science  } Minia University 8/13 Java Programming 4. I/O and Confirmation Dialog Boxes Example program written in two ways // Average3JOptionPane.java // Average three ints. Use JOptionPane. import javax.swing.*; public class Average3JOptionPane { public static void main(String[] args) { int a, b, c, average; String temp; // Temporary storage for JOptionPane input. //... Read three numbers from dialog boxes. temp = JOptionPane.showInputDialog(null, "First number"); a = Integer.parseInt(temp); // Convert String to int. temp = JOptionPane.showInputDialog(null, "Second number"); b = Integer.parseInt(temp); temp = JOptionPane.showInputDialog(null, "Third number"); c = Integer.parseInt(temp); //... Compute their average. average = (a + b + c) / 3; //... Display their average in a dialog box. JOptionPane.showMessageDialog(null, "Average is " + average); } Java Programming - Prof. Moheb Ramzy Girgis } Dept. of Computer Science - Faculty of Science  Minia University Confirmation Dialogs You have used showMessageDialog to display a message dialog box and showInputDialog to display an input dialog box. Occasionally it is useful to answer a question with a confirmation dialog box. A confirmation dialog can be created using the following statement: When a button is clicked, the method returns an option value. The value is JOptionPane.YES_OPTION (0) for the Yes button, JOptionPane.NO_OPTION (1) for the No button, and JOptionPane.CANCEL_OPTION (2) for the Cancel button. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 9/13 Java Programming 4. I/O and Confirmation Dialog Boxes Confirmation Dialogs: Example A simple program to illustrate how to create and use the confirmation dialog. import javax.swing.JOptionPane; public class ConfirmationDialog { public static void main(String[] args) { int answer = JOptionPane.showConfirmDialog(null, "Select a button"); if (answer == JOptionPane.YES_OPTION) JOptionPane.showMessageDialog(null, "You have selected YES button"); else if (answer == JOptionPane.NO_OPTION) JOptionPane.showMessageDialog(null, "You have selected NO button"); else if (answer == JOptionPane.CANCEL_OPTION) JOptionPane.showMessageDialog(null, "You have selected CANCEL button"); Java Programming - Prof. Moheb Ramzy Girgis } Dept. of Computer Science - Faculty of Science  } Minia University Confirmation Dialogs: Example A simple program to illustrate how to create and use the confirmation dialog. import javax.swing.JOptionPane; public class ConfirmationDialog { public static void main(String[] args) { int answer = JOptionPane.showConfirmDialog(null, "Select a button"); 0) if (answer == JOptionPane.YES_OPTION) JOptionPane.showMessageDialog(null, "You have selected YES button"); 1) else if (answer == JOptionPane.NO_OPTION) JOptionPane.showMessageDialog(null, "You have selected NO button"); 2) else if (answer == JOptionPane.CANCEL_OPTION) JOptionPane.showMessageDialog(null, "You have selected CANCEL button"); Java Programming - Prof. Moheb Ramzy Girgis } Dept. of Computer Science - Faculty of Science  } Minia University 10/13 Java Programming 4. I/O and Confirmation Dialog Boxes Confirmation Dialogs: Example The results of three runs of the example program: Run 1 Run 2 Run 3 Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Formatting Console Output To display only two digits after the decimal point in a floating- point value, you may write the code like this: double x = 2.0 / 3; System.out.println("x is " + (int)(x * 100) / 100.0); It is better to format the output using the printf method. The syntax to invoke this method is: System.out.printf(format, item1, item2,..., itemk) where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, Boolean value, or a string. A simple specifier consists of a percent sign (%) followed by a conversion code. Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 11/13 Java Programming 4. I/O and Confirmation Dialog Boxes Formatting Console Output (Continued) Some frequently used simple specifiers: Example: Output Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University Formatting Console Output (Continued) Items must match the specifiers in order, in number, and in exact type. By default, a floating-point value is displayed with six digits after the decimal point. You can specify the width and precision in a specifier, as shown in the following examples: Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 12/13 Java Programming 4. I/O and Confirmation Dialog Boxes Formatting Console Output (Continued) Now we can display only two digits after the decimal point in a floating-point value using the printf method as follows: double x = 2.0 / 3; System.out.printf("x is %4.2f", x); The output will be: x is 0.67 By default, the output is right justified. We can put the minus sign (-) in the specifier to specify that the item is left justified in the output within the specified field. For example, the following statements System.out.printf("%8d%8s%8.1f\n", 1234, "Java", 5.6); System.out.printf("%-8d%-8s%-8.1f \n", 1234, "Java", 5.6); Output Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science  Minia University 13/13

Use Quizgecko on...
Browser
Browser