package calculator;
import java.util.Scanner;
/**
*
* @author Kevin
*/
public class Calculator {
/**
* This method prints a message, a prompt passed as a parameter,
* to the screen and then scans input until an int is entered. The user
* may type other input without error but the method would not end until
* an int is entered in. It then returns the int that was entered
* @param prompt a message describing the input that is desired
* @return an int, entered by the user on the keyboard
*/
public static int getIntFromUser(String prompt){
Scanner sc = new Scanner(http://System.in);
System.out.println(prompt);
while(!sc.hasNextInt()){
sc.next();
}
return sc.nextInt();
}
/**
* This method prints a message, a prompt passed as a parameter,
* to the screen and then returns the first character entered as input.
* The user may type more than a single character but only the first
* character entered will be returned.
* @param prompt a message describing the input that is desired
* @return a char, taken from the first position of text entered by the
* user on the keyboard
*/
public static char getCharFromUser(String prompt){
Scanner sc = new Scanner(http://System.in);
System.out.println(prompt);
String input = sc.nextLine();
return input.charAt(0);
}
/**
* This method should determine the proper mathematical operation needed
* based on the parameter op, which is a char type and should contain
* a symbol such as '+' or '*' to indicate the mathematical operation
* desired. The parameters x and y will be used to complete the mathematical
* operation and the result will be returned.
* @param x leading operand, this value will be before the operator
* @param y trailing operand, this value will be after the operator
* @param op this char will store a symbol representing the operation that
* should take place
* @return the answer to the mathematical equation formed by x, y, and op.
*/
public static int solveProblem(int x, int y, char op){
/*fill in code*/
return 0;
}
/*Add all future methods in this space*/
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x = getIntFromUser("Enter an int");
int y = getIntFromUser("Enter an int");
char op = getCharFromUser("Enter an operation symbol");
int ans = solveProblem(x, y, op);
System.out.println( x + " " + op + " " + y + " = " + ans);
}
}
以上是代码以及解释。。。我也是个新手这个是我刚刚做完的。
值得注意的是,我在下面一个方法里面写的是 /*fill in code*/.
在这里我们可以直接用if else 去填充.(我真的萌新,专业术语也不会hhh)
public static int solveProblem(int x, int y, char op) {
if (op == '+') {
return x + y;
} else if (op == '-') {
return x - y;
} else if (op == '*') {
return x * y;
} else if (op == '/') {
return x / y;
} else if (op == '^') {
// return (int) (Math.pow((double) x, (double) y));
return exp(x,y);
}
return 0;
}
public static int exp(int x, int y) {
int ans = 1;
for (int i = 0; i < y; i++) {
ans *= x;
}
return ans;
这是我在刚刚需要填写代码里面填写的,上面有 if else 去限定情况,下面自己做了一个方法以供我直接使用。(还有两种其他方法我怕太乱就没弄上去)
加油加油!