Well, I seem to have some little error. Purpose: Finding Max and Min numbers from txt file by inputting four numbers. Then I calculate the Range by using (Max - Min)

Problem: It does great with positive numbers. However, when I input negative numbers, calculation seems to be off.

For example 98 -46 74 -66 it would give me 140.0, in which the real answer is 172.

I.e#2 35 -16 -84 -99 it would give me 99, answer would be near 134.

Here is my work -

import java.util.*;
import java.io.*;



public class Range4 {

	public static void main (String [] args) throws FileNotFoundException
{
	Scanner fin = new Scanner(new FileReader("data.txt"));

	double range;

	int count = 1;
	double integer = 0.0;
	double max = 0.0;
	double min = 999.0;

	integer = fin.nextDouble();


while( fin.hasNext() ) {
	count++;

	integer = fin.nextDouble();

	if(integer >= max)
	{
		max = Math.max(max,integer);

	}

	if(integer <= min)
	{
		min = Math.min(min,integer);

	}

		}
	range = max - min;

	System.out.println("range is " + range);

	}

}

Just need a little guidance. Do I have to do another loop, where I have to do something with the negatives? Do I have to initialize the max to another number besides 0? Any help is appreciated.

Recommended Answers

All 2 Replies

the problem is that you are making it skip the first number by using

integer = fin.nextDouble();

before the while loop. in the examples you gave if the first number is not there the answer is correct
98 -46 74 -66 -- without the first number, 98, the answer is 140
35 -16 -84 -99 -- without the first number, 35, the answer is 83

the problem is that you are making it skip the first number by using

integer = fin.nextDouble();

before the while loop. in the examples you gave if the first number is not there the answer is correct
98 -46 74 -66 -- without the first number, 98, the answer is 140
35 -16 -84 -99 -- without the first number, 35, the answer is 83

Alright thank you very much. I guess I overlooked it, as once I deleted that statement, it was working perfectly. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.