简体   繁体   中英

How do I make a variable array size?

So my program is functional. I just want it to use a binary search of a text file and determine the highest index number it can be found in. If it cannot be found it finds the next largest and makes it a negative. My problem is right now the array size that gets made is 11. That is because it is how many integers are in the text file I am using. What if I will not know the number of integers? I understand people suggest making a list but will that not accept repetitions? why does this section of code:

while(scanner.hasNextInt()){
        arr[i++] = scanner.nextInt();}
    scanner.close();

not change my array size as necessary?

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class BinarySearch {   
 public static int binarysearch(int[] arr, int key)
{
int lo = 0, hi = arr.length - 1;
{
    while (lo < hi) 
    {
        int mid = (lo + hi) / 2;
        if (arr[mid] <= key)
            lo = mid + 1;
        if (arr[mid] > key)
            hi = mid;
    }
    if (arr[lo] == key) {
        return lo;
    }
    else if ((arr[lo] != key) && (arr[lo-1] == key)){
        return lo - 1;
    }
    else{
    return (binarysearch( arr,(key-1))* - 1); 
} 
    }
} 



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

    int k = Integer.parseInt(args[1]);
    Scanner scanner = new Scanner(new File(args[0]));

    int[] arr = new int[11];
    int i = 0;
    while(scanner.hasNextInt()){
        arr[i++] = scanner.nextInt();}
    scanner.close();

    System.out.println(binarysearch(arr, k));

}}
}

List

A List is a Collection often used instead of arrays. Specifically, the ArrayList implementation of List is backed by arrays internally, and handles re-sizing or re-building the internal array as needed, automatically.

List< Integer > integers = new ArrayList<>() ;
integers.add( 7 ) ;
integers.add( 11 ) ;

To find the highest, sort using the Collections utility class.

Collections.sort( integers ) ;

For reverse order:

Collections.reverse( integers ) ;

If you know roughly the size your list might end up needing, you can specify the initial capacity when instantiating your ArrayList . Setting the initial capacity can help with making ArrayList run a little more efficiently, but you need not worry about this.

int initialCapacity = ( myNumberOfThis * myNumberOfThat ) + 1 ;  // Whatever clues you have about possible size.
List< Integer > integers = new ArrayList<>( initialCapacity ) ;

See the Oracle Tutorial .

If you want to eliminate duplicates, use a Set instead. Search Stack Overflow as this has been covered many many times already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM