public class Calculator {
public static void main(String[] args) {
DecimalFormat df=new DecimalFormat("0.##");
if (args.length !=3) {
System.out.println(
"Usage: java Calculator operand1 operator operand2\n");
System.exit(0);
}
double result=0;
switch (args[1].charAt(0)){
case '+': result=Double.parseDouble(args[0]) +
Double.parseDouble(args[2]);
break;
case '-': result=Double.parseDouble(args[0]) -
Double.parseDouble(args[2]);
break;
case '*': result=Double.parseDouble(args[0])*
Double.parseDouble(args[2]);
break;
case '/': result=Double.parseDouble(args[0]) /
Double.parseDouble(args[2]);
}
System.out.print(df.format(Double.parseDouble(args[0]))+' '+
(args[1])+' '+
df.format(Double.parseDouble(args[2]))+" = "+
result+"\n");
}
}
public class Calculator {
public static String validateInput(String [] ss){
String message = "";
// if(...){
// message += " No oprator in the second postion;";
// }
// if(...){
// message += " Too many operands";
// }
return message;
}
public static void main(String[] args) {
String sMessage = validateInput(args);
if(sMessage.trim().length() != 0){
System.out.println(" error in input : " + sMessage);
System.out.println(
"Usage: java Calculator operand1 operator operand2\n");
}
for(String s: args){
System.out.println(s);
}
if (args.length !=3) {
System.out.println(
"Usage: java Calculator operand1 operator operand2\n");
System.exit(0);
}
int result=0;
if(args[1].equals("\\\\*"))args[1]= "*";
System.out.println(args[1].charAt(0));
switch (args[1].charAt(0)){
case '+': result=(int) Double.parseDouble(args[0]) +
(int) Double.parseDouble(args[2]);
break;
case '-': result=Integer.parseInt(args[0]) -
Integer.parseInt(args[2]);
break;
case '*': result=(int)Double.parseDouble(args[0])*
(int) Double.parseDouble(args[2]);
break;
case '/': result=Integer.parseInt(args[0]) /
Integer.parseInt(args[2]);
}
System.out.print(args[0]+' '+ args[1]+' '+args[2]
+" = "+result+"\n");
}
}
Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.
TRUSTED BY
You want to throw exception rather than deal with therror and write a message
in case your method is supposed to be used by ither people fior calling in theier
programs (or by youerslef form diffferent classes) then exception will help you in a sens that you can defere
handling the stuation oto the calling calss/method
If you are writing this methiod for this particular application I'd
rather not throw exceptions