我相当擅长Java和OOP,因此即使API是彻底的,Java中的许多概念也没有完全合理。我已经制作了一个小的计算器代码,但是我想学习如何使用方法中的参数来实现相同的产品,样本将是素数。
import java.io.IOException;
import java.util.Scanner;
public class Ga {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
switch (s) {
case '+':
System.out.println("Result= "+(i+z));
System.in.read();
break;
case '-':
System.out.println("Result= "+(i-z));
System.in.read();
break;
case '*':
System.out.println("Result= "+(i*z));
System.in.read();
break;
case '/':
System.out.print("Result= "+(i/z));
System.in.read();
break;
}
}
}
答案 0 :(得分:1)
要从OOP开始,您可以编写一个表示操作的抽象类:
public abstract class Operation {
public abstract float getResult(float a, float b);
}
然后,尝试编写像Addition,Division:
这样的具体操作public class Addition extends Operation {
@Override
public float getResult(float a, float b) {
return a + b;
}
}
public class Division extends Operation {
@Override
public float getResult(float a, float b) {
return a / b;
}
}
然后,重写你的主要方法:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Operation op = null;
switch (s) {
case '+':
op = new Addition();
break;
case '-':
op = new Subtraction();
break;
...
}
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}
正如理查德提到的那样,你也可以用HashMap重写开关:
public static void main(String[] args) throws IOException {
System.out.println("First number:");
float i = input.nextInt();
System.out.println("Choose operator +, -, *, /");
char s = input.next().charAt(0);
System.out.println("Second number:");
float z = input.nextInt();
Map<String, Operation> operationMap = new HashMap<String, Operation>();
operationMap.put("+", new Addition());
operationMap.put("-", new Substraction());
...
Operation op = operationMap.get(s);
System.out.println("Result= " + op.getResult(i, z));
System.in.read();
}
答案 1 :(得分:0)