I am taking a lynda dot com course online to start off. The course asks you to write a simple program:
- Ask the user to input 2 values
- Ask the user to input an operation
- Use the operation on the 2 values and print the result
This was very different from the solution given by the course. Could anyone take a quick look at it and tell me if there's something I'm doing fundamentally wrong or inefficient? My suspicion is that I'm using too much memory.
package com.example.java;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a numeric value: ");
String input1 = scanner.nextLine();
System.out.print("Enter a numeric value: ");
String input2 = scanner.nextLine();
double double1 = Double.parseDouble(input1);
double double2 = Double.parseDouble(input2);
System.out.print("Choose and operation (+ - * /): ");
String input3 = scanner.nextLine();
double resultAdd = double1 + double2;
double resultSub = double1 - double2;
double resultMul = double1 * double2;
double resultDiv = double1 / double2;
switch (input3) {
case "+":
System.out.println("The answer is " + resultAdd);
break;
case "-":
System.out.println("The answer is " + resultSub);
break;
case "*":
System.out.println("The answer is " + resultMul);
break;
case "/":
System.out.println("The answer is " + resultDiv);
break;
}
}
}
Here is what the instructor wrote, for the record:
package com.example.java; import java.util.Scanner; public class Calculator2 { public static void main(String[] args) { String s1 = getInput("Enter a numeric value: "); String s2 = getInput("Enter a numeric value: "); String op = getInput("Choose an operation (+ - * /):"); double result = 0; try { switch (op) { case "+": result = addValues(s1, s2); break; case "-": result = subtractValues(s1, s2); break; case "*": result = multiplyValues(s1, s2); break; case "/": result = divideValues(s1, s2); break; default: System.out.println("Unrecognized operation!"); return; } System.out.println("The answer is " + result); } catch (Exception e) { System.out.println("Number formatting exception " + e.getMessage()); } } private static double addValues(String s1, String s2) { double d1 = Double.parseDouble(s1); double d2 = Double.parseDouble(s2); return d1 + d2; } private static double subtractValues(String s1, String s2) { double d1 = Double.parseDouble(s1); double d2 = Double.parseDouble(s2); return d1 - d2; } private static double multiplyValues(String s1, String s2) { double d1 = Double.parseDouble(s1); double d2 = Double.parseDouble(s2); return d1 * d2; } private static double divideValues(String s1, String s2) { double d1 = Double.parseDouble(s1); double d2 = Double.parseDouble(s2); return d1 / d2; } private static String getInput(String prompt) { System.out.print(prompt); Scanner sc = new Scanner(System.in); return sc.nextLine(); } }