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

最初に表示されるエラーは、 level という名前のString 変数ではなくString "level"を試行し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 に答える