can this java calculator program be modified for my learning purpose?
This works just fine, but as you can see their is no "constructor" in this program! And their is only a scanner object! Can this program be more simplified in a way it has constructors and methods, as an example for me to learn ?
import java.util.Scanner;
public class calc {
public static void main(String args[]){
Scanner calculator = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Enter first number: ");
fnum = calculator.nextDouble();
System.out.println("Enter second number: ");
snum = calculator.nextDouble();
System.out.println("enter any operator: ");
String op = calculator.next();
switch (op){
case ("x") :
answer = fnum * snum;
System.out.println(answer);
break;
case ("/") :
answer = fnum / snum;
System.out.println(answer);
break;
case ("+") :
answer = fnum + snum;
System.out.println(answer);
break;
case ("-") :
answer = fnum - snum;
System.out.println(answer);
break;
}
}
}
Re: can this java calculator program be modified for my learning purpose?
Please use code tags when posting code.
Sure, you could use OO principles to improve this code. What have you tried?
Re: can this java calculator program be modified for my learning purpose?
Im sorry ... im new to this forum world
If u can give me an example ... easy for me to understand or change my code adding constructors and methods, it would really be appreciated ... im trying to learn about methods , objects and constructors using simple examples, a calculator in above case ..
Re: can this java calculator program be modified for my learning purpose?
Recommended reading: Lesson: Classes and Objects (The Java™ Tutorials > Learning the Java Language)
Why don't you read through that and try to apply the ideas yourself, then we'll go from there.
Re: can this java calculator program be modified for my learning purpose?
I am already following those lessons , but the practical examples given are not very helpful because they are limited ..
Thats why i posted this simple calculator program , which i learned from Bucky's java video tutorials..
I just want a simple program to demonstrate , "objects" , "methods" and "constructors" ... !!
so that i can make my logic clear on them ... my theory on these 3 is clear although ..
Re: can this java calculator program be modified for my learning purpose?
Well, you could create a Calculator class that has methods for doing the different operations, and then call those methods based on user input.