user102817
user102817

Reputation: 307

First Java Program: Random data in my Array?

Problem: Write a program that reads a list of real numbers. After the program ends it should print out only the unique numbers. That is, only numbers that appear once in the list. If there are more than 50 unique numbers on the list, then you should only print the first 50.

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


public class Hmwk {

public static void main(String[] args) throws FileNotFoundException {
    Scanner input=new Scanner (new File ("input.txt"));
    int n = 0;
    final int MAX_SIZE = 50;
    double[] numbersArray = new double[MAX_SIZE];
    while (input.hasNextDouble() && n<MAX_SIZE){
        double in = input.nextDouble();
        if (inList(in,numbersArray))
            numbersArray[n]=in;
            n++;

    }
    printReport(numbersArray);
}


public static boolean inList(double number, double[] list){
    for (double i : list)
        {
            if (i == number){
                return false;
        }

    }
    return true;
}


public static void printReport(double[] list)
{
    System.out.println("The unique numbers were");
    System.out.println(Arrays.toString(list));

}


}

input.txt file=

5.0 6.0 7.0 8.9 3.0 2.0 8.9 8.9 9.0 7.0 6.0 5.0 4.0 3.0 2.0 1.0

results- The unique numbers were [5.0, 6.0, 7.0, 8.9, 3.0, 2.0, 0.0, 0.0, 9.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

No idea where I'm going wrong here, I think its my inlist method? Any and all help is much appreciated. Thanks!

Upvotes: 0

Views: 81

Answers (3)

Mike Harris
Mike Harris

Reputation: 1576

You are incrementing n whether the number is already in the list or not. What you've written is (re-indented for clarity):

if (inList(in,numbersArray))
            numbersArray[n]=in;
n++;

But it should be:

if (inList(in,numbersArray)) {
            numbersArray[n]=in;
            n++;
}

Then when you're done, truncate the list to be n elements long.

Upvotes: 0

Dhana Krishnasamy
Dhana Krishnasamy

Reputation: 2176

Your if needs braces

if (inList(in,numbersArray)){
            numbersArray[n]=in;
            n++;
}

or do this

if (inList(in,numbersArray))
                numbersArray[n++]=in;

Upvotes: 1

Kick
Kick

Reputation: 4923

Add bracket for IF condition

if (inList(in,numbersArray))
{
            numbersArray[n]=in;
            n++;
}

Upvotes: 1

Related Questions