Home > other >  Unable to correctly input scanned string into 2D array
Unable to correctly input scanned string into 2D array

Time:09-17

I am to read the file and compile running totals on the salespeople and also their total for each individual product and the overall total for each product. I must store all of that in a 2D array(Lists are not allowed) and print in a certain format.

The text file is documented as such:

1,4,10.20
2,2,17.20
etc 
etc

Column1 is personID Column 2 is product number column 3 is the amount

My code attempts to split each line into a string and then further split each value to an index and then store it within a 2D array. I feel silly but I am having a conversion error. No matter what I do I cannot make the array store amount in an acceptable format. I can't create the array as a double for some reason. It returns as terminated when I attempt to compile. My professor said an integer should work and I simply cannot get accurate summing.

package HW1;

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

public class salesList {

      public static void main(String[] args) throws FileNotFoundException{
          Scanner salesList;
          salesList = new Scanner(new File("C:\\Users\\mjwag\\OneDrive\\cs151/salesList.txt"));
          
         while  (salesList.hasNext())  {
             Scanner file = salesList;
             file.nextLine();
             String line = file.nextLine();
             String[] lineArray = line.split(",");
             int personID = Integer.parseInt(lineArray[0]);
             int product = Integer.parseInt(lineArray[1]);
             int amount = Integer.parseInt(lineArray[2]);
             int [][] sales = new int[4][6];
             sales[personID-1][product-1]  = amount;
             
            }
         
      }
}

CodePudding user response:

The easiest way to store both integers and doubles in an array is to use Number, which is a superclass of both Integer and Double. For example:

Number[][] sales = new Number[4][6];
...
sales[0][0] = 1;
sales[0][1] = 4.5;

Alternatively, as you've discussed with your professor, it's possible to convert a double to an integer and lose the numbers after the decimal point. This can be done as follows:

double val = 4.5;
int intVal = (int) val;
  • Related