user4027720
user4027720

Reputation:

Trying to remove numbers bigger than my target number

I'm trying to fill an array with numbers from a file and I can't seem to figure out how to remove numbers larger than my target "D".

Here is the code where I'm having the problem

public static void populateMatrix(int[] s){
    File input = new File("set2.txt");
    int value;

    try{
        Scanner inf = new Scanner(input);

        for(int i = 0; i < s.length ; i++){
            value = inf.nextInt();
            if(value > D){
                //Don't know what to add here.
            }//if
            else{
                s[i] = value;
            }//else

        }//for
    }//try

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

}//PopulateMatrix 

Upvotes: 0

Views: 80

Answers (3)

Jake Huang
Jake Huang

Reputation: 140

Read next number if value >D

or

for(int i = 0; i < s.length i++;){
    value = inf.nextInt();
    if(value <= D){
        s[i] = value;
    }

Upvotes: 1

dekajoo
dekajoo

Reputation: 2102

Assuming you don't want empty space into your array I'll do this :

public static void populateMatrix(int[] s){
    File input = new File("set2.txt");
    int value;

    try{
    Scanner inf = new Scanner(input);

    for(int i = 0; i < s.length ;){
        value = inf.nextInt();
        if(value <= D){
            s[i] = value;
            i++;
        }
    }//for
    }//try

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

}//PopulateMatrix 

Upvotes: 1

Compass
Compass

Reputation: 5937

Arguably, you could just keep pulling an int using a while loop and then assign it when it qualifies.

for(int i = 0; i < s.length ; i++){
    value = inf.nextInt();
    while(value > D){
        value = inf.nextInt();
    }
    s[i] = value;
 }

Obviously, if you run out of ints to get next of, this will throw an error, but there wasn't any checking before so it'll still be up to you to error-check regardless.

Upvotes: 2

Related Questions