Search code examples
javaarraysobjecttraversal

array traversal algorithm to load the array with Rationals


I have a java class already made up of methods and am in the process of creating a driver java class and just need some help figuring out how to load my traversal array with rationals. I have the following but I need help figuring out how to load it with the rationals.

    public static void main(String [] args)
       {
       //Creates the array
          Rational[] rats = new Rational[6];
          for(int i=0; i < rats.length; i++)
          { 
             rats[i] = new Rational(2,18); //this will call constructor. 
             //{4/5, 4/19, 3/8, 9/3, 2/4, 24/7 }; I want to load these into the array instead of
             // just 2,8 (2/8) (numerator, denominator)

          }

I have two constructors, an EVC and DVC named public Rational() and public Rational(int num,int den) thanks.


Solution

  • Initialize the array doing

    Rational[] rationals = new Rational[] { new Rational(2, 18), new Rational(4, 5), ... };
    

    (Sorry I couldn't name the array rats lol).

    EDIT:

    If you're going to load the numbers from a file, you can do something like

    Scanner scanner = new Scanner(file);
    int currentRational = 0;
    while (scanner.hasNext()) {
      int num = scanner.nextInt();
      int den = scanner.nextInt();
      scanner.nextLine();
      rationals[currentRational] = new Rational(num, den);
      currentRational++; 
    }
    

    This is assuming your file has this format

    10 3
    4 5
    etc.