gpt4 book ai didi

java - 如何在java中有效地使用方法中的参数?

转载 作者:行者123 更新时间:2023-12-01 13:04:00 27 4
gpt4 key购买 nike

我对 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;
}

}
}

最佳答案

要开始使用 OOP,您可以编写一个表示操作的抽象类:

public abstract class Operation {
public abstract float getResult(float a, float b);
}

然后,尝试编写加法、除法等具体运算:

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;
}
}

然后,像这样重写你的 main 方法:

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();
}

正如 Richard 提到的,您还可以使用 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();

}

关于java - 如何在java中有效地使用方法中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362759/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com