Java Scanner没有采用有效输入或与解析整数相关的其他问题

时间:2016-01-05 09:58:55

标签: java

请参阅以下与数学表实践相关的代码。对于15 * 9以外的所有数字的乘法,它可以正常工作但是15 * 9有问题。

package com.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class Entry {

    static Scanner scanIn;
    static Random random;
    static List<String> list;
    static List<String> mistakeList;
    static File mistakeFile;

    static {
        scanIn = new Scanner(System.in);
        random = new Random();
        list = new ArrayList<String>();

    }

    /**
     * Main function to call the private methods.
     */
    public static void main(String[] args) throws IOException {
        mistakeFile = new File(args[0]);
        if(!mistakeFile.exists())
        {
            try {
                mistakeFile.createNewFile() ;
            } catch (IOException e) {           
                e.printStackTrace();
            }
        }
        mistakeList = getFileContent(mistakeFile);
        System.out.println("Please enter max limit .....");
        Integer maxLimit = Integer.parseInt(scanIn.nextLine());

        System.out.println("Please enter min limit .....");
        Integer minLimit = Integer.parseInt(scanIn.nextLine());

        System.out.println("Enter the number if iterations ..... ");
        Integer iterations = Integer.parseInt(scanIn.nextLine());

        executeTable(maxLimit, minLimit, iterations);
        scanIn.close();
        writeIntoFile();
    }
    /**
     * 
     * Multiplication logic which outputs two numbers, take input from user and 
     * matches it with result of multiplicaion.
     */
    private static void executeTable(Integer maxLimit, Integer minLimit,
            Integer iterations) {
        int skipCount = 0;
        for (int iTemp = 0; iTemp < iterations; iTemp++) {
            try
            {
            Integer num1 = getNextRandomInt(minLimit, maxLimit);
            Integer num2 = getNextRandomInt(2, 9);
            if (list.contains(num1 + "_X_" + num2) && skipCount < 10) {
                iTemp = iTemp - 1;
                skipCount++;
                continue;
            }
            skipCount = 0;
            System.out.println(num1 + " X " + num2 + " = ");
            Integer usrAnswer = Integer.parseInt(scanIn.nextLine());
            Integer answer = num1 * num2;
            if (usrAnswer != answer) {
                System.out.println("WRONG!! The correct answer is  " + num1
                        + " X " + num2 + " = " + answer);
                if(!mistakeList.contains(num1 + "_X_" + num2))
                {
                    mistakeList.add(num1 + "_X_" + num2);
                }
            } else {
                if(!list.contains(num1 + "_X_" + num2))
                {
                    list.add(num1 + "_X_" + num2);
                }
            }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

        }

    }

    /**
     * Gets next random number
     * 
     */
    private static Integer getNextRandomInt(Integer minLimit, Integer maxLimit) {
        Integer number = random.nextInt();
        if(maxLimit < minLimit)
        {
            maxLimit = maxLimit + minLimit ;
            minLimit = maxLimit - minLimit ;
            maxLimit = maxLimit - minLimit ;
        }

        number = (number % (maxLimit - minLimit + 1));
        if (number < 0) {
            number = -number;
        }
        number += minLimit;
        return number;
    }

    /**
     * Records commom mistake in file
     */
    private static void writeIntoFile() throws IOException 
    {
        String fileContent = "" ;
        for(String data : mistakeList)
        {
            fileContent = fileContent +data+ "\r\n" ;
        }
        try (FileWriter fw = new FileWriter(mistakeFile.getAbsoluteFile(), false);
                BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(fileContent);
            bw.close();
        }

    }

    /**
     *Returns file content.
     *
     */
    private static List<String> getFileContent(File file) {
        List<String> lst = new ArrayList<String>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                lst.add(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return lst;
    }
}

The console output is as follows .

Please enter max limit .....
15

Please enter min limit .....
15

Enter the number if iterations ..... 
100

15 X 2 = 
30

15 X 8 = 
120

15 X 9 = 
135

WRONG!! The correct answer is  15 X 9 = 135

虽然提供了135个正确的输入,但上述程序显示错误。 不知道15 * 9

的问题

添加更多说明。

上述程序在限制内生成两个随机数,用户必须为其输入正确答案。示例。上述程序显示两个数字,如&#34; 15 X 8 =&#34;并且用户必须输入120.上述程序适用于除&#34; 15 X 9 =&#34;以外的所有其他组合。用户输入135,这是正确的答案仍然是程序显示错误答案。

2 个答案:

答案 0 :(得分:1)

问题在于:

if (usrAnswer != answer) {

您正在比较Integer个对象,必须这样做:

if (usrAnswer.equals(answer)) {

!=的比较检查对象实例是否相同。它适用于较小数字的原因是实例被缓存到一定限度。

在这种情况下,更好的解决方案是使用原始int类型:

int usrAnswer = Integer.parseInt(scanIn.nextLine());
int answer = num1 * num2;
if (usrAnswer != answer) {

答案 1 :(得分:1)

这是因为将对象与==进行比较。问题在于以下几个方面:

Integer usrAnswer = Integer.parseInt(scanIn.nextLine());
Integer answer = num1 * num2;
if (usrAnswer != answer)
  • Integer.parseInt(scanIn.nextLine())使用int返回Integer,然后将自动框返回Integer.valueOf()
  • num1 * num2将使用num.intValue() 取消装箱两个操作数,执行乘法,结果为int,然后自动装箱使用Integer将其加入Integer.valueOf()

Integer类中,值[-128,127]被缓存,因此Integer.valueOf(55)每次都会返回相同的对象,而Integer.valueOf(135)每次都会返回一个新对象。

  • 在第三行中,您将2个Integer个对象与参考比较==进行比较。当Integer的值在缓存范围内时,两个对象都是相同的,否则它们是不同的对象。

要解决此问题,建议您将Integer更改为int

int usrAnswer = Integer.parseInt(scanIn.nextLine());
int answer = num1 * num2;
if(usrAnswer != answer)

或将两个Integer对象与.equals()进行比较:

if(!usrAnswer.equals(answer))