java - 如果玩家输入错误,java程序如何添加一个返回代码的函数
问题描述
我的程序有问题不在于代码是我将如何做到这一点,这是我被困住的令人困惑的部分。只是为了让你知道我是一个基本的 Java 编码器我不懂复杂的东西所以请记住我的代码不是最好的。
-------------------------------------------------- --------- 程序说明--------------------------- -------------------------- 在我向您展示我的问题之前,让我们开始解释它是如何工作的,好的,当您执行程序时提示您类似于视频游戏中的菜单,但它是基于文本的,它向您显示不同的选项,例如输入玩家详细信息、播放数学游戏节目分数然后退出。输入玩家详细信息它告诉玩家 1 输入他/她的姓名,然后告诉另一个人输入他/她的玩家姓名,然后提示您返回菜单。玩数学游戏是要求玩家 1 输入他/她的数学方程式,之后玩家 2 必须解决它,如果他做对了,他得到 10 分,如果没有,玩家根本没有得到任何分数。然后重复另一个玩家输入他/她的数学方程式,然后提示您返回菜单。显示分数 它显示谁在数学游戏中得分最高 它计算出谁的分数最高 如果他们两个都得到相同的分数然后意味着平局然后提示您返回菜单。最后一件事是退出选项,当您选择该选项时,它会停止程序。如果玩家选择了错误的选项,他会收到一条错误消息并让您返回菜单
好的,这是第一个名为 menu 的类,其他与名为 game fations 的菜单相关的类
菜单:https: //gist.github.com/LOLMEHA/86ff28b038d85030e346785e953644e0 游戏阵营:https ://gist.github.com/LOLMEHA/f05a51e07c8823a0e65cebbf81cc52ef
所以这部分代码我自己也很难弄出来
import java.util.*;
public class Gamefunctions // this is a core when player choosess one of these options from the menu
{
String[] player =new String[2];
double scorea = 0; // verribles of all the objects
double scoreb = 0;
int i;
Scanner input = new Scanner(System.in);
double answer = 0;
double numA, numB;
char operator;
char operator2;
boolean quit = false;
double sum1;
double sum2;
public void enterDetails(){ // if player select enter details
for ( i=0;i<2;i++) {// tell's player to input he/she's name and stores them
int c=i;
System.out.println("Welcome to the maths quiz game please input player name "+c++);
player[i] = input.next();
}
}
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
if () {
if (operator == '+') {// this is if operator is one of these like +-*/^ and then it works out the sum
answer = numA + numB;
}
if (operator == '-') {
answer = numA - numB;
}
if (operator == '*') {
answer = numA * numB;
}
if (operator == '/') {
answer = numA / numB;
}
if (operator == '^') {
answer = Math.pow(numA, numB);
}
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
System.out.println("");
System.out.println(player[1]+"\t solve the equation"); // tells other player to slove the equation
sum2 = input.nextDouble();
if (sum2 == answer){// checks if the answer from the player is good or not if its good he/she gets 10 points if he/she gets it wrong gets no points and shows the right answer so the player learns from his/she mistakes
scoreb = scoreb + 10.00;
System.out.println("correct you got 10 points to your score");
System.out.println("");
} else{
System.out.println("incorrect you got no points the correct answer was:"+"" + answer);
}
您知道程序何时要求玩家输入他的数学方程式并输出它并继续程序并等待用户输入
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
假设玩家输入像这样的 10+10 输入,但由于它们存储在 int 的 numA 中,所以它不起作用,我想发出一条错误消息,说你不能像这样输入 10+10 你必须输入像这样 10 enter + enter 10 enter 所以如果玩家输入正确它将能够工作它将继续程序
因此,如果您对我对问题的解释有任何问题,请询问,以便我可以编辑它,谢谢您的时间:)
解决方案
这是我要查看的代码的一部分:
String s = input.next();
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
首先,有几个挑剔:Java 不是 C。您不需要在代码块的开头声明所有变量。numA
,numB
并且operator
永远不会在这段代码之外使用,因此在这里声明它们也是有意义的。
你也使用input.next()
一次Double.parseDouble()
,然后input.nextDouble()
下一次。坚持一个或另一个,如果某些东西不能正常工作,它会使调试更容易。
最后,如果有人进入会发生什么10 +1 0
?该错误被静默忽略,因为1
被拾取为operator
字符串的一部分,然后被charAt(0)
. 这里一种更有弹性的解析方法是先获取整个,然后在调用之前String
检查。length == 1
charAt(0)
double numA = input.nextDouble();
String operatorString = input.next();
char operator;
if (operatorString.length() == 1) {
operator = operatorString.charAt(0);
} else {
// Handle error
}
double numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
那么问题来了:我们如何检测无效输入?看一下Scanner#nextDouble()
(重点是我的)的文档:
public double nextDouble()
将输入的下一个标记扫描为双精度。如果下一个标记无法转换为有效的双精度值,此方法将抛出。
InputMismatchException
如果翻译成功,扫描仪会超过匹配的输入。
所以我们知道nextDouble()
可以为我们检测到无效输入。它以异常的形式执行此操作,我们可以使用语句侦听(或catch ):try ... catch
try {
double numA = input.nextDouble();
} catch (InputMismatchException e) {
System.err.printf("Invalid input! Expected number, found '%s'.\n", input.next());
}
我们可以扩展它并将整个代码部分包装在一个 中try ... catch
,但是如果用户犯了一个错误,就必须重新开始。一个更用户友好的解决方案是:
double numA;
while (1) {
try {
numA = input.nextDouble();
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected number, found '%s'.\n", input.next());
}
}
请注意,即使您不打印它,input.next()
也需要调用 to 以防止无限循环。
现在我们只需要为 做类似的事情operator
:
char operator;
while (1) {
String operatorString;
try {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
operator = operatorString.charAt(0);
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected character, found '%s'.\n", operatorString);
}
}
这似乎与前面的数字片段非常相似 - 让我们尝试将这里的一些常见代码重构为一个方法:
@FunctionalInterface
public interface ScannerGetter<T> {
T apply() throws InputMismatchException;
}
public <T> T getValueFromScanner(ScannerGetter<T> getter, String type) {
while(1) {
try {
return getter.apply();
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected %s.");
}
}
}
在这几行中发生了很多事情。第一部分声明了一个函数式接口——这基本上是一种自定义类型的 lambda 函数。我们稍后再谈。
方法本身 ( getValueFromScanner()
) 是一个通用方法。它允许我们使用具有不同类型的相同方法来代替泛型参数( T
),而无需复制它。
这就是您如何使用上述方法来检索您的三个输入:
double numA = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
char operator = this.<Char>getValueFromScanner(() -> {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
return operatorString.charAt(0);
}, "operator");
double numB = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
// Once your code gets here, all three variables will have valid values.
推荐阅读
- google-cloud-firestore - 在不存在的文档下使用 Firestore 中的子集合是一种好习惯吗?
- sql - SQL - 标记多于 1 列的条件不为空
- c++ - 转换忽略 sf::Sprite 的起源
- javascript - day.js 没有将 UTC 转换为本地时间
- ansible - mysql_db - 删除所有数据库
- automated-tests - ObjChildItem.Click() 在循环中无法正常工作
- javascript - DataTable Column Reorder 将数据映射到错误的列中
- python - 是否可以在不实际使用鼠标的情况下使用手势控制来实现鼠标的功能
- r - 如何像记事本一样阅读文字?
- html - Html 仅在大于最大高度时显示滚动