Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone! I want to read some two elements from a file!
My file is something like that:
180 2.3
25 0.12 //the first element is number of games the second the cost of each games
to store these data i have thought to make a 2d array and put them inside.Unfortunately,i do not know each time how many lines my file has.So, i have thought to count the number of lines make my array and after that put my data in the array. This does not work.
something else i would like to ask, what type my array would be??

What I have tried:

I have tried this, i know I have mistakes but how can fix it??
Java
        while(sc.hasNextLine()){  //count the numbers of lines
            sc.nextLine();
            numlines++;
        }
float a1[][]= new float a1[numlines][2];
int c=0; 
while(sc.hasNext()){
        a1[c][0]=sc.nextInt();
        a1[c][1]=sc.nextFloat();
        c++
}
System.out.println(Array.deeptoString(a1));

could you suggest me something to fix my code and make it to work??
Posted
Updated 20-May-20 2:56am
v3

1 solution

You are confused about what a multidimensional array is.
A bidimensional array uses two integer indices to store a single value of a specific type.
In your case, you need to create a class holding the quantity and cost; then you can put some instances of this class into a list (more flexible) or into a single-dimension array (less flexible since you have to know how many elements the array will contain upon its creation).
And you should always use BidgDecimal type to store and do comptations on values which represent money (float and double type are not recommended for that, since their floating-point nature can lead to rounding errors).
Java
public class GameLine
{
   private int Quantity;
   private BigDecimal Cost;

   // Define getters, setters, and constructor
}

Then, you can create a list of GameLine objects, and upon iteration of your text file, for each line create a new GameLine object and add it to the list. At the end of the procedure, you can turn your list into an array, if needed, but that shouldn't be necessary.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900