Results 1 to 3 of 3
Thread: can anyone help me
- 01-09-2008, 02:33 AM #1
Member
- Join Date
- Dec 2007
- Posts
- 3
- Rep Power
- 0
can anyone help me
Hii all...
Hope you all are doing great.
I am actually trying to read an input text file. The file has some points, with each line having only one point. Like:
(1.0,1.0)
(0.0,2.0)
(1.0,2.0)
(1.0,0.0)
and so on.
I want to read and store them one by one, then add one with the another so that I will be able to get an output (3.0,5.0) (which I got by adding all the points).
Now I am able to read the points from a file. But I could not store them add them one with the other. can anyone help me with this issue.
- 01-09-2008, 02:41 AM #2
For each point use StringTokenizer to get ordinates. Convert to Number using Float.parseFloat method. You can store this number in an ArrayList.
When you are done reading the file. Loop over the array list and add get sum of both the ordinates.
And Bingo !!dont worry newbie, we got you covered.
- 01-09-2008, 04:18 AM #3
Java Code:import java.io.*; import java.util.*; public class AddingPoints { public static void main(String[] args) { String path = "addingPoints.txt"; Scanner scanner = null; try { scanner = new Scanner(new File(path)); } catch(FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); } List<Double[]> list = new ArrayList<Double[]>(); while(scanner.hasNextLine()) { String line = scanner.nextLine(); Double[] array = parse(line); System.out.printf("array = %s%n", Arrays.toString(array)); list.add(array); } scanner.close(); System.out.println("------------------"); double[] total = addPoints(list); System.out.printf("total = %s%n", Arrays.toString(total)); } private static Double[] parse(String s) { double[] d = new double[2]; int left = s.indexOf("("); int comma = s.indexOf(","); d[0] = Double.parseDouble(s.substring(left+1, comma)); int right = s.indexOf(")"); d[1] = Double.parseDouble(s.substring(comma+1, right)); return new Double[] { Double.valueOf(d[0]), Double.valueOf(d[1]) }; } private static double[] addPoints(List<Double[]> list) { double x = 0; double y = 0; for(int j = 0; j < list.size(); j++) { Double[] array = (Double[])list.get(j); x += array[0].doubleValue(); y += array[1].doubleValue(); } return new double[] { x, y }; } }


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks