1

我正在编写一个程序来解决简单的数学问题。我想要做的是使它即使我在扫描仪级别输入一个字符串也不会给我一个错误。该级别是选择数学问题的难度。我已经尝试过 parseInt,但现在不知道该做什么。

import java.util.Random;
import java.util.Scanner;
public class Test { 
    static Scanner keyboard = new Scanner(System.in);
    static Random generator = new Random();
    public static void main(String[] args) {
        String level = intro();//This method intorduces the program,
        questions(level);//This does the actual computation.
    }
    public static String intro() {

        System.out.println("HI - I am your friendly arithmetic tutor.");
        System.out.print("What is your name? ");
        String name = keyboard.nextLine();
        System.out.print("What level do you choose? ");
        String level = keyboard.nextLine();
        System.out.println("OK " + name + ", here are ten exercises for you at the level " + level + ".");
        System.out.println("Good luck.");
        return level;
    }
    public static void questions(String level) {
        int value = 0, random1 = 0, random2 = 0;
        int r = 0, score = 0;
        int x = Integer.parseInt("level");
        if (x==1) {
            r = 4;          
        }       
        else if(x==2) {
            r = 9; 
        }
        else if(x==3) {
            r = 50; 
        }
        for (int i = 0; i<10; i++) {
            random1 = generator.nextInt(r);//first random number.
            random2 = generator.nextInt(r);//second random number.
            System.out.print(random1 + " + " + random2 + " = ");
            int ans = keyboard.nextInt();
            if((random1 + random2)== ans) {
                System.out.println("Your answer is correct!");
                score+=1;
            }
            else if ((random1 + random2)!= ans) {
            System.out.println("Your answer is wrong!");
            }
        }
        if (score==10 || score==9) {
            if (score==10 && x == 3) {
                System.out.println("This system is of no further use.");
            }
            else {
                System.out.println("Choose a higher difficulty");
            }
            System.out.println("You got " + score + " out or 10");
        }
        else if (score<=8 && score>=6) {
            System.out.println("You got " + score + " out or 10");
            System.out.println("Do the test again");
        }
        else if (score>6) {
            System.out.println("You got " + score + " out or 10");
            System.out.println("Come back for extra lessons");
        }
    }
}
4

1 回答 1

0

我看到的第一个错误是您尝试Integer.parseInt()使用字符串“级别”而不是名为级别的字符串变量

    int x = Integer.parseInt("level");

应该

    int x = Integer.parseInt(level);

此外,在定义级别时,您可以使用keyboard.nextInt而不是keyboard.nextLine

String level = keyboard.nextInt();

然后,您以后不必进行Integer.parseInt()操作

于 2013-06-20T17:25:40.700 回答