I have a method that reads in a file. The first line of the file has an integer that shows how many additional lines there are. Each additional line after that has a pair of two double values (no commas)
For Example:
4
13 15
20.2 33.5
24 38
30 31
etc.
I have two static double arrays, x and y. For each line after the first, I want to assign the first double in the set to x, and the second double in the set to y. However, i'm not 100% sure what to do how to assign. This is my code so far: (note that line is a call to another method not shown)
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the data file.");
fileName = input.nextLine();
while(input.hasNext())
{
int num = input.nextInt(); // the first line integer
line.x[0] = input.nextDouble(); //the additional line x coordinate
line.y[0] = input.nextDouble(); //the additional line y coordinate
}
The only problem is, how do I increment the value of x and y from [0] to [1], [2], 3, etc for each additional line in the file, based on what the first line int value 'num' is, so that I don't keep overwriting [0]?
For example, in the example above, the value of 'num' is 4, because there are four additional lines after it. How do I increase (+=) the value of x and y by one based on the value of num? I know this sounds stupid but I'm stumped at this point.
The only problem is, how do I increment the value of x and y from [0] to [1], [2], 3, etc for each additional line in the file, based on what the first line int value 'num' is, so that I don't keep overwriting [0]?
Use a counter i
int num = input.nextInt(); // the first line integer
int i = 0;
while(input.hasNext())
{
line.x[i] = input.nextDouble(); //the additional line x coordinate
line.y[i++] = input.nextDouble(); //the additional line y coordinate
}
line.x[0] = input.nextDouble();
This assigns the next value read to the first slot in the array x belonging to an object called line
(I'm assuming that line is an object you have instantiated and that x is a public field of that object...)
You want to increment an index and use that to address your arrays:
int i = 0;
while(input.hasNext())
{
int num = input.nextInt(); // the first line integer
line.x[i] = input.nextDouble(); //the additional line x coordinate
line.y[i] = input.nextDouble(); //the additional line y coordinate
i ++;
}
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.