java - Java 测验(平均猜测)

标签 java math

我正在用 Java 编写一个问答游戏,但我不知道如何找到用户猜测的平均次数。这是简单代码的游戏:

import java.util.Scanner;
import java.io.File;

public class JavaQuiz 
{
    public static void main(String[] args) throws Exception
    {

        Scanner input = new Scanner(System.in);

        File file = new File("questions.txt");

        Scanner scan = new Scanner(file);
        String line;
        double lineNum = 0;
        int skip = 0;
        int correct = 0;
        double guesses = 0;

        while(scan.hasNextLine()){
            // Counting of the line number
            lineNum = lineNum + 1;
            // Scanning the next line
            line = scan.nextLine();

            // Declaring the delimeter.
            String delimiter = "\\|";
            // Splitting the line
            String[] temp = line.split(delimiter);

            // Print out the questions
            System.out.println(temp[0]);

            // Wait for the user to input
            String keyboard = input.next();
            // Take the space off the answer
            String two = temp[1].replaceAll("\\s","");

            if(keyboard.equals("q")){
                skip = skip + 1;
            }

            else{

                while(!(keyboard.equals(two)) && !(keyboard.equals("q"))){


                    keyboard = input.nextLine();

                    if(keyboard.equals("q")){
                        skip = skip + 1;
                    } else {
                        System.out.println("Incorrect. Please Try Again");
                    }

                } 

                    if(keyboard.equals(two)){
                        correct = correct + 1;
                    }
            }

        }

        System.out.println("You got " + correct + " Questions Correct.");
        System.out.println("You skipped " + skip + " questions.");
        System.out.println("And for the questions you completed, you averaged " + avg + " guesses.");        
    }
}

我应该做这样的事情吗?

double avg = guesses / lineNum;

无论如何,我得到的答案都是 0。

最佳答案

此行之后:String Keyboard = input.next(); 你应该做这样的事情:

if(!(keyboard==null))
    guesses++;

那么你是对的:avg=guesses/lineNum;

*提示guesses & lineNum应该是int,其中guesses代表他回答的次数,lineNum代表行数。这里不需要加倍

int 在 Ram 上占用的空间比 double 少

关于java - Java 测验(平均猜测),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14637501/

相关文章:

java - 模型 boolean 属性值未显示在 HTML 中(Spring MVC)

Builder 中的 Java 泛型

java - 无法打开数据库/无法将(数据库)的区域设置更改为 'en_US'

java - 2D字符格式数组

Java 数字/数学抽象

c - 为什么 stdlib.h 的 abs() 函数族返回有符号值?

java - 从jsp传递参数到DAO中的sql查询

c++ - 乘法游戏循环幻灯片问题

math - 如何存储多项式?

iphone - 音频 - 构建/生成并播放纯波形