如何根据用户输入声明变量?

问题描述 投票:1回答:1

我正在尝试创建一个程序来拼写检查用户键入的内容。他们必须正确键入'type'一词10次,它会显示一条消息,指出要花多长时间。我的问题是,结尾永远不会消失,它会不断要求您输入“ type”。我相信这是因为'while (attempts < required)'。我认为我需要做出必要的=正确的尝试。 if attempt = type,则将产生1个正确值。任何帮助表示赞赏。也很抱歉,我不知道如何构建问题

    public static void printHeading(String heading) {

        System.out.println(heading.toUpperCase());

        for (int i = 0; i < heading.length(); i++)
            System.out.print("=");
        System.out.println();
        System.out.println();
    }


    public static int runTutorial(Scanner in, String word, int required) {
        Scanner sc = new Scanner(System.in);
        String attempt = word;
        int correct = 0;
        int attempts = 0;

        while (attempts<required) 
        {
            System.out.print("Enter '" + word + "': ");
            attempt = sc.nextLine();

            if(attempt.equals("type")) {

                System.out.println("Correct");
            }   
            else {
                System.out.println("Try again");
            }
        }
        return attempts;

    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final int TIMES = 10; //required number of correct repetitions
        final String WORD = "type"; //the word to type
        long startTime, endTime; //start and end time of typing test
        double seconds; //elapsed time in seconds
        int attempts;

        printHeading("Typing Tutor");
        System.out.println("You need to type a word " + TIMES +
                           " times correctly, as quickly as you can");
        System.out.println("Your word today will be '" + WORD + "' (do not enter the quotes)");
        System.out.println();
        System.out.println("Type anything and press enter to begin");

        //The test
        System.out.println("Press enter to start the test");
        sc.nextLine();
        startTime = System.currentTimeMillis();
        attempts = runTutorial(sc, WORD, TIMES);
        endTime = System.currentTimeMillis();

        //Test report
        seconds = (double)(endTime - startTime) / 1000;
        System.out.println("You took " + seconds + " seconds and " + attempts +
                           " attempts to correctly type '" + WORD + "' " + TIMES + " times");
        System.out.println();
        printHeading("Come back for more pracice soon");
    }

}
java user-input variable-declaration
1个回答
0
投票

System.out.println("Correct");下,您需要增加attempts变量,否则它将保持为0。

if(attempt.equals("type")) {

    System.out.println("Correct");
    attempts++; // <-- here
} 
© www.soinside.com 2019 - 2024. All rights reserved.