java 编程如何添加一个函数,如果玩家输入错误则返回代码
java program how add a function that goes back code if player has inputted it wrong
我的程序有问题,不是代码问题,而是我将如何执行它,这是我遇到的令人困惑的部分。只是想让你知道我是一个基本的 java 编码员,我不懂复杂的东西,所以请记住我的代码不是最好的。
-------------------------------------------- -------------- 程序说明-------------------------------- ------------------------------
在我向您展示我的问题之前,让我们开始解释它是如何工作的,好的,当您执行该程序时,它会提示您有点像视频游戏中的菜单,但它是基于文本的,它会向您显示不同的选项,例如输入玩家详细信息,玩数学游戏显示分数,然后退出。 enter player details 它告诉玩家 1 输入 he/she 名称,然后告诉另一个玩家输入 he/she 玩家名称,然后提示您返回菜单。玩数学游戏是玩家 1 被要求输入 he/she 数学方程式,之后玩家 2 必须解决它,如果他做对了,他会得到 10 分,如果没有,玩家根本没有得分。然后重复另一个玩家输入 he/she 数学方程,然后提示您返回菜单。显示分数 它显示谁在数学游戏中获得了最多的分数 如果他们都获得相同的分数,它会计算谁获得最多然后意味着平局然后提示您返回菜单。最后一件事是退出选项,当您选择该选项时它会停止程序。如果玩家选择了错误的选择,他会收到一条错误消息并将您带回菜单
好的,这是第一个 class 菜单和其他 class,它与名为游戏派系的菜单相关联
菜单: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 enter 但它不起作用,因为它们存储在 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
,然后在调用 charAt(0)
.
之前检查 length == 1
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()
Scans the next token of the input as a double. This method will throw InputMismatchException
if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
所以我们知道 nextDouble()
可以为我们检测无效输入。它以异常的形式执行此操作,我们可以使用 try ... catch
语句侦听(或 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()
来防止无限循环。
现在我们只需要为 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.
我的程序有问题,不是代码问题,而是我将如何执行它,这是我遇到的令人困惑的部分。只是想让你知道我是一个基本的 java 编码员,我不懂复杂的东西,所以请记住我的代码不是最好的。
-------------------------------------------- -------------- 程序说明-------------------------------- ------------------------------ 在我向您展示我的问题之前,让我们开始解释它是如何工作的,好的,当您执行该程序时,它会提示您有点像视频游戏中的菜单,但它是基于文本的,它会向您显示不同的选项,例如输入玩家详细信息,玩数学游戏显示分数,然后退出。 enter player details 它告诉玩家 1 输入 he/she 名称,然后告诉另一个玩家输入 he/she 玩家名称,然后提示您返回菜单。玩数学游戏是玩家 1 被要求输入 he/she 数学方程式,之后玩家 2 必须解决它,如果他做对了,他会得到 10 分,如果没有,玩家根本没有得分。然后重复另一个玩家输入 he/she 数学方程,然后提示您返回菜单。显示分数 它显示谁在数学游戏中获得了最多的分数 如果他们都获得相同的分数,它会计算谁获得最多然后意味着平局然后提示您返回菜单。最后一件事是退出选项,当您选择该选项时它会停止程序。如果玩家选择了错误的选择,他会收到一条错误消息并将您带回菜单
好的,这是第一个 class 菜单和其他 class,它与名为游戏派系的菜单相关联
菜单: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 enter 但它不起作用,因为它们存储在 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
,然后在调用 charAt(0)
.
length == 1
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()
Scans the next token of the input as a double. This method will throw
InputMismatchException
if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
所以我们知道 nextDouble()
可以为我们检测无效输入。它以异常的形式执行此操作,我们可以使用 try ... catch
语句侦听(或 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()
来防止无限循环。
现在我们只需要为 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.