package afterfeb13;
import java.util.Scanner;
public class calculator {
static int c = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input for a:");
int a = sc.nextInt();
System.out.println("Enter input for b:");
int b = sc.nextInt();
int d = add(a, b);
System.out.println("add : " + d);
int f = sub(a, b);
System.out.println("sub : " + f);
int e = multiple(a, b);
System.out.println("multi : " + e);
float g = div(a, b);
System.out.println("div : " + g);
}
private static int div(int a, int b) {
c = a / b;
return c;
}
private static int multiple(int a, int b) {
c = a * b;
return c;
}
private static int sub(int a, int b) {
c = a - b;
return c;
}
private static int add(int a, int b) {
c = a + b;
return c;
}
}
Output:
Enter input for a:
1548
Enter input for b:
576
add : 2124
sub : 972
multi : 891648
div : 2.0
Different way calculator:Scanner class as static
package afterfeb13;
import java.util.Scanner;
public class cal {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("calculatore");
add();
sub();
multiple();
div();
}
private static void div() {
System.out.println("div Enter input for a:");
int a = sc.nextInt();
System.out.println("div Enter input for b:");
int b = sc.nextInt();
int c = a / b;
System.out.println("add of a/b:" + c);
}
private static void multiple() {
System.out.println("multiple Enter input for a:");
int a = sc.nextInt();
System.out.println("multiple Enter input for b:");
int b = sc.nextInt();
int c = a * b;
System.out.println("add of a*b:" + c);
}
private static void sub() {
System.out.println("sub Enter input for a:");
int a = sc.nextInt();
System.out.println("sub Enter input for b:");
int b = sc.nextInt();
int c = a - b;
System.out.println("sub of a-b:" + c);
}
private static void add() {
System.out.println("add Enter input for a:");
int a = sc.nextInt();
System.out.println("add Enter input for b:");
int b = sc.nextInt();
int c = a + b;
System.out.println("add of a+b:" + c);
}
}
Output:
calculatore
add Enter input for a:
12
add Enter input for b:
23
add of a+b:35
sub Enter input for a:
23
sub Enter input for b:
4
sub of a-b:19
multiple Enter input for a:
23
multiple Enter input for b:
34
add of a*b:782
div Enter input for a:
45
div Enter input for b:
5
add of a/b:9
Reference(TBD):https://www.tpointtech.com/Scanner-class
Java Scanner Class Constructors(TBD)
Java Scanner Class Methods(TBD)
Top comments (2)
Modern approach using Java 8 features:
lambdas, Streams, Maps, Exception Handling,...
You might think this is too much for a calculator. But its preferred where future modifications, extensions, and error handling are important in production.
Output:
Thanks bro