英文:
Get random operators and integers
问题
以下是翻译好的代码部分:
public static char getOperator(int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;
break;
case 2: operator = '*';
answer = x * y;
break;
case 3: operator = '/';
answer = x / y;
break;
default: operator = '?';
}
return operator;
}
请注意,我已经将代码中的字符文字('+'、'-'、'*'、'/'、'?')更改为字符直接表示,而不是使用实体编码。
英文:
im doing an assignment which requires me to create 3 classes.
- 1 with getting 2 random integers,
- 1 with getting random operators such as + - * / which should be done so in char method
- the last one to check if the simple mathematics answer is correct using booleans via user Scanner input.
i need a little help here as im not sure if i've done the random operators method correctly and am really lost at how i should tabulate both random int and operators together in one class.
here's the code i've done so far:
public static char getOperator (int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;;
break;
case 2: operator = '*';
answer = x * y;;
break;
case 3: operator = '/';
answer = x / y;;
break;
default: operator = '?';
}
return operator;
}
答案1
得分: 1
我相信你的意思是你需要创建3个方法(而不是类)。
- 一个方法用于生成随机整数(创建一个返回两个整数的方法而不是调用两次返回一个整数的方法,这是一个不好的设计)。
- 一个方法返回随机运算符。
- 一个方法检查由“随机数字 随机运算符 随机数字”组成的操作是否等于用户输入。
无论如何,这里有很多要理清楚的地方:
你的第一个方法getTwoIntegers是不正确的,你要求输入两个整数,但实际上从未使用它们,然后返回一个随机数。
getOperator方法需要重新设计,不需要输入,并返回一个字符(等于+ - x /)。
最终的方法将两次调用第一个方法,然后一次调用第二个方法,然后打印操作供用户查看,并检查响应是否正确。
希望这可以帮助你更好地构思应该如何构建你的代码。
我没有发布源代码,因为我认为如果你尝试自己做(这是一个任务),这对你来说会更好。
祝你好运,玩得开心
英文:
I believe you mean you need to create 3 methods (and not classes).
- One that creates a random integer (it's a bad design to create a
method that returns two integers instead of just calling two times
one that returns one int). - One that returns a random operator
- One that checks if an operation consisting of "random-number
random-operator random-number" is equal to user input
Anyways, there's a lot to unpack here, so:
Your first method getTwoIntegers is incorrect, you're asking for two integers in input but you never actually use them, then you return one random number.
The method getOperator needs to be redesigned to have no input and return one char (equal to + - x /).
Your final method will call the your first method twice, then the second method once, it will then print the operation for the user to see, and check if the response is correct.
Hopefully this can help you conceptualize better the way you should build your code.
I didn't post the source code since I believe it's much better for you if you try to do it by yourself (this being an assignment and all)
Good luck and have fun
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论