Hi, I have a question regarding my code here. It's a simple calculator. It's not necessarily wrong, but I think there is a shorter, better way to do this.
Here is the code:
import javax.swing.*; public class Java_calculator_3_4 { static void addition () { int a = Integer.parseInt(JOptionPane.showInputDialog("Please enter the first value:")); int b = Integer.parseInt(JOptionPane.showInputDialog("Please enter the second value:")); int answer = (a+b); System.out.println("\nThe answer is " + answer); } static void subtraction () { int a = Integer.parseInt(JOptionPane.showInputDialog("Please enter the first value:")); int b = Integer.parseInt(JOptionPane.showInputDialog("Please enter the second value:")); int answer = (a-b); System.out.println("\nThe answer is " + answer); } static void multiplication () { int a = Integer.parseInt(JOptionPane.showInputDialog("Please enter the first value:")); int b = Integer.parseInt(JOptionPane.showInputDialog("Please enter the second value:")); int answer = (a*b); System.out.println("\nThe answer is " + answer); } static void division () { int a = Integer.parseInt(JOptionPane.showInputDialog("Please enter the first value:")); int b = Integer.parseInt(JOptionPane.showInputDialog("Please enter the second value:")); int answer = (a/b); System.out.println("\nThe answer is " + answer); } public static void main(String[] args) { String arithmeticOperation; char selection; System.out.println("Possible arithmetic operations:\n a\t Addition\n b\t Subtraction\n c\t Multiplication\n d\t Division"); arithmeticOperation = JOptionPane.showInputDialog("Which arithmetic operation would you like to initiate?"); selection = arithmeticOperation.charAt(0); switch (selection) { case 'a': addition(); break; case 'b': subtraction(); break; case 'c': multiplication(); break; case 'd': division(); break; default: System.out.println("You choice is invalid"); } System.exit(0); } }
I'm trying to figure out how I can convert the code so the 'InputDialog' only has to be written once, preferably within the Main Method like the 'arithmeticOperation', and then from there transfer the two entered numbers as arguments back to the methods to be calculated. This means the output also only has to be programmed once. Same issue.
I'm not sure where to begin here, and how to adjust the code accordingly. So any advice and tips would be greatly appreciated.
Thanks