Search code examples
javareadfile

reading from a file wont read the first value Java


So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns "Your Initial Fib is out of range, eneter # between 1-10" Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?

private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;

public static void main(String[] args) throws IOException
{

    inFile = new File( inFileName);
    Scanner in = new Scanner (inFile);
    outFile = new PrintWriter (outFileName);
    int valueCounter = 1;
    while (in.hasNextInt())
    {
        int value = in.nextInt();
        if ( value <= 39 && value >= 1 && valueCounter == 2)
        {
            lengthValue = value;
            valueCounter ++;
        }
        if ( value > 39 || value < 1 && valueCounter == 2)
        {
            System.out.println("You are asking for too many Fib, eneter # between 1-39");
            in.close();
            System.exit(1);
        }
        if ( value <= 10 && value >= 1 && valueCounter == 1)
        {
            startValue = value;
            valueCounter ++;
        }
        if ( value > 10 || value < 1 && valueCounter == 1)
        {
            System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
            in.close();
            System.exit(1);
        }
    }
}

Solution

  • It is because of operator precedence, the && is evaluated before the ||. This makes the following expression

    if ( value > 10 || value < 1 && valueCounter == 1)
    

    evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.