我在短时间内编写了Java代码,因此我不知道为什么我的System.exit(0)
命令无效。
该程序测试用户的一年级或二年级数学。它接收两个“随机”数字,用户回答算术问题。当程序询问用户是否要再次播放时,输入N代表No似乎不会注册包含System.exit(0)的if语句。程序只是重新启动,就像用户输入Y一样。
import java.util.*;
class Tester {
public static void main (String[] args) {
SuperRandom randomNumberGenerator = new SuperRandom();
Scanner scan = new Scanner (System.in);
int selection, q1_1, q1_2, q1_3, q1_4, q1_5, questans;
int score = 0;
int a;
int b, i;
String scanchoice;
String choice = "Y";
final int numberOfQuestions = 5;
int getNextRandom;
int answer;
while (choice == "Y"){
System.out.println ("Welcome to Math Tester 2.0.");
System.out.println ("");
System.out.println ("Please enter your grade level:");
System.out.println ("1. 1st Grade Test");
System.out.println ("2. 2nd Grade Test");
System.out.println ("3. Quit Math Tester 2.0");
selection = scan.nextInt();
if (selection == 1) {
System.out.println ("Enter: " +selection);
System.out.println ("");
for (i=1; i<=5; i++){
a = randomNumberGenerator.getNextRandom(numberOfQuestions);
b = randomNumberGenerator.getNextRandom(numberOfQuestions);
System.out.println ("What is " +a + " + " +b + "?");
answer = a+b;
questans = scan.nextInt();
System.out.println("" +questans);
if (questans == answer){
score++;
}
}
System.out.println ("");
System.out.println ("Max points possible: 5.");
System.out.println ("Your score: " +score);
System.out.println ("Do you wish to play again (Enter Y for Yes or N for No)?");
choice = scan.next();
if (choice = "N") {
System.out.println ("Goodbye!");
System.exit(0); //Exits program if user entered N.
}
if (choice = "Y");
choice = "Y";
}
if (selection == 2){
System.out.println ("Enter: " +selection);
System.out.println ("");
}
if (selection == 3){
System.out.println ("Goodbye!");
System.exit(0);
}
}
}
}
答案 0 :(得分:0)
System.exit()
未在您的代码中执行,因为您的if/else
条件不正确。
使用equals
进行字符串比较而不是==。
答案 1 :(得分:0)
根据Juned Ahsan'anwer中的评论,您应该将=
更改为==
或.equals()
,例如在这一行中if (choice = "N") {
它应该是if (choice.equals("N")) {
虽然==
在您的情况下不起作用,但您应该使用.equals()
=
是一个赋值运算符,其中==
是关系运算符