Using Java: Problem 1: We will use methods in class javax.swing.JOptionPane such
ID: 3790310 • Letter: U
Question
Using Java:
Problem 1:
We will use methods in class javax.swing.JOptionPane such as showMessageDialog and showInputDialog to get two numbers from the user and to compute their sum and product and display this info.
Create a Class called ArithmeticUsingSwing, that has the static main method. In the main method, get two numbers as input from the user using JOptionPane.showInputDialog (static) method just like we studied in class. This method can take a String parameter (note that this method actually can take any Object as its parameter). This method also returns a String. So we cannot assign it directly to an int. We can convert a String to an int (assuming that the String is actually an integer value) using the static method Integer.parseInt defined in java.lang.Integer class as follows. Suppose the String is in variable called val, we use int num = Integer.parseInt(val) to get the integer value represented in val and assign it to int variable num.
Display the results of addition and multiplication in a dialog box using JOptionPane.showMessageDialog method.
Explanation / Answer
import javax.swing.JOptionPane;
public class ArithmeticUsingSwing {
public static void main(String[] args) {
String input1 = JOptionPane.showInputDialog("Input Number 1"); //Display input field
int num1 = Integer.parseInt(input1); //Parse the value into integer
String input2 = JOptionPane.showInputDialog("Input Number 2"); //Display input field
int num2 = Integer.parseInt(input2); // Parse the value into integer
JOptionPane.showMessageDialog(null, "Sum: " + (num1 + num2)
+ " Product: " + num1 * num2); //Display output in message box
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.