Java 如果用户出错,如何让系统退出?
如果用户猜错了,系统打印错误。我想在用户出错时结束游戏,有人能帮我吗?我尝试使用一个系统出口,但是当猜测正确的时候,它就退出了。我希望系统打印“游戏结束”,如果用户是错误的,并为下一张卡出现之后Java 如果用户出错,如何让系统退出?,java,arrays,Java,Arrays,如果用户猜错了,系统打印错误。我想在用户出错时结束游戏,有人能帮我吗?我尝试使用一个系统出口,但是当猜测正确的时候,它就退出了。我希望系统打印“游戏结束”,如果用户是错误的,并为下一张卡出现之后 static Scanner console = new Scanner(System.in); public static void main(String[] args) { int[] cards = {6,4,2,7,5,9,11,1,12}; Syst
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] cards = {6,4,2,7,5,9,11,1,12};
System.out.println("predict next number by typing in 'higher' or 'lower'");
for (int i = 1; i < cards.length; i++)
{
printHead(cards, i);
System.out.println("");;
String predict = console.next();
if (predict.equals("higher"))
checkHigher(cards, i-1, i);
if (predict.equals("lower"))
checkLower(cards, i-1, i);
}
printAll(cards);
}
public static void printAll(int[] cards){
for (int i =0; i< cards.length; i++)
System.out.print(cards[i]+ " ");
}
public static void printHead(int[] cards, int upTo){
for (int i =0; i< upTo; i++)
System.out.print(cards[i]+ " ");
}
public static void checkHigher (int[] cards, int pos1, int pos2){
if (cards[pos2]>cards[pos1])
System.out.println ("Correct!");
else
System.out.println("Wrong");
}
public static void checkLower (int[] cards, int pos1, int pos2){
if (cards[pos2]<cards[pos1])
System.out.println ("Correct!");
else
System.out.println("Wrong");
}
}
静态扫描仪控制台=新扫描仪(System.in);
公共静态void main(字符串[]args){
int[]卡片={6,4,2,7,5,9,11,1,12};
System.out.println(“通过输入'higher'或'lower'预测下一个数字”);
对于(int i=1;i卡片[pos1])
System.out.println(“正确!”);
其他的
System.out.println(“错误”);
}
公共静态无效检查下限(int[]卡,int pos1,int pos2){
如果(卡片[pos2]只需在每个错误答案后键入:
System.exit(0);
我试着使用一个系统出口,但当猜测被取消时,它正在退出
也对
这可能是因为您使用了else语句istead of else代码块。忘记大括号了吗?更简单的方法是使用
System.exit(0);
另一种方法是从每次检查中返回一个布尔值
,并使用它来决定是否退出
第三种选择是将main
方法代码包装在try-catch
中,并在用户出错时通过Exception
退出
使用代码片段遵循三个备选方案:
直接退出检查
public static void checkLower (int[] cards, int pos1, int pos2){
if (cards[pos2]<cards[pos1]) {
System.out.println ("Correct!");
} else {
System.out.println("Wrong");
System.exit(0);
}
}
抛出异常
public boolean void checkLower (int[] cards, int pos1, int pos2) throws Exception {
if (cards[pos2]<cards[pos1]) {
System.out.println ("Correct!");
} else {
System.out.println("Wrong");
throw new Exception("Wrong answer");
}
}
“我尝试使用系统退出,但猜测正确时该退出。”您是否忘记在您的两条语句周围添加{
和}
?如果用户错误,我希望系统打印“游戏结束”,然后…
-所以您想退出系统或打印一些内容?
if (!checkLower(cards, i-1, i)) {
System.exit(0);
}
public boolean void checkLower (int[] cards, int pos1, int pos2) throws Exception {
if (cards[pos2]<cards[pos1]) {
System.out.println ("Correct!");
} else {
System.out.println("Wrong");
throw new Exception("Wrong answer");
}
}
public static void main(String[] args) {
try {
// Your code here
} catch (Exception e) {
System.out.println("There was an exception in the input");
}
}