所以我最近开始编写一个计算器,它将提供1-50的两个随机数和*, +
或-
符号。但是,我不太确定如何实际检查用户输入的答案是否正确,因为我实际上无法计算答案。任何帮助都会非常感谢。
下面的代码(也很抱歉没有注释)
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, what is your name?"); //Asks the childs name
Scanner demo = new Scanner(System.in); //creates the scanner
String a = demo.nextLine();
System.out.println("Hi " + a + " I hope your ready for the quiz");
System.out.println("Lets begin");
String [] arr = {"*", "+", "-"};
Random random = new Random();
Random no = new Random();
for(int counter1= 1; counter1 <=1;counter1++){
int select = random.nextInt(arr.length);
int firstnumber;
for(int counter= 1; counter <=1;counter++){
firstnumber = no.nextInt(50);
int firstnumber2;
firstnumber2 = no.nextInt(50);
System.out.println(firstnumber + " " + arr[select] + " " + firstnumber2);
int b = demo.nextInt();
答案 0 :(得分:3)
您必须使用if
(或switch
)才能了解如何计算输入。
int result = 0;
if (arr[select].equals("*")
result = firstnumber * secondnumber; // do not call it firstnumber2
else if (arr[select].equals("+")
result = firstnumber + secondnumber;
else // if (arr[select].equals("-")) - else if not needed if only three elements are used
result = firstnumber - secondnumber;
switch
:
switch(arr[select]) {
case "*": result = firstnumber * secondnumber;
break;
case "+": result = firstnumber + secondnumber;
break;
case "-": result = firstnumber - secondnumber;
break;
default: break;
}
答案 1 :(得分:0)
有几种方法可以解决这个问题。一个好的风格如下:
@FunctionalInterface
interface CalcFunction{
int calc(int a , int b);
}
HashMap<String , CalcFunction> operations = new HashMap<>();
operations.put("*" , (a , b) -> a * b);
operations.put("/" , (a , b) -> a / b);
operations.put("+" , (a , b) -> a + b);
operations.put("-" , (a , b) -> a - b);
//select a random operation
String op = generateOperation();
//generate operands
int a = randomNumber();
int b = randomNumber();
//the correct result
int expected = operations.get(op).calc(a , b);
这种方法的优点是它可以通过额外的操作轻松扩展。
编辑:
基本思想是映射每个表达式&#34; *&#34;,&#34; /&#34;,&#34; +&#34;,&#34; - &#34;到CalcFunction
的实例,它在calc
中完全实现了该操作。由于CalcFunction
是Functional Interface
,因此可以用lambda表示。
(a , b) -> a * b
例如也可以表示为
new CalcFunction(){
int calc(int a , int b){
return a * b;
}
}