C Or Java Help Needed! - Programming - Nairaland
Nairaland Forum › Science/Technology › Programming › C Or Java Help Needed! (799 Views)
1 Reply
| C Or Java Help Needed! by Nobody: 3:47pm On Aug 10, 2013 |
Please I need a C or preferably, Java code that could scan through a text file (a file contaning string of numbers stored in a notepad. The file contains something like 534135635652652663346.....). The code will store two numbers at a time in an integer variable, the code will then find the average of the cumulative number. Thanks in anticipation of your help. |
| Re: C Or Java Help Needed! by naijaswag1: 7:36pm On Aug 10, 2013 |
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pdf; import java.io.File; import java.io.FileNotFoundException; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; /** * * @author naija_swag */ public class NumberScanner { public static void main(String[] args) throws FileNotFoundException { //use the attached picture to see the location of file for the file string File file = new File(System.getProperty("user.dir" ![]() + "/src/pdf/input.in" ;//read in your file Scanner s = new Scanner(file); String str = null; //if it is only the average that is needed double average = 0; int count = 0; //if you need to print the numbers, we keep them here LinkedList<Integer> listNum = new LinkedList<Integer>(); Integer num = null; //loop through the file reading one line at a time while (s.hasNext()) { str = s.nextLine(); //split the string read so we can loop thru and pair numbers String[] arr = str.trim().split("" ;String sss = ""; //loop through array of strings for (int i = 1; i < arr.length; i++) { sss += arr[i]; //does the magic of making sure we pick out two consecutive numbers //uses modulus for that purpose if (i % 2 == 0) { num = Integer.parseInt(sss); average += num; count++; listNum.add(num); sss = ""; } else if (i % 2 != 0 && i == arr.length - 1) { num = Integer.parseInt(sss); listNum.add(num); count++; } } } Iterator itil = listNum.iterator(); double num2 = 0; while (itil.hasNext()) { num2 += (Integer) itil.next(); } System.out.printf("Our Average is %.3f %n", num2 / listNum.size()); System.out.printf("Our Average is %.3f", average / count); } }
|
| Re: C Or Java Help Needed! by Nobody: 9:05am On Aug 11, 2013 |
Thanks Bros, I will try it and report back. |
How To Make Money From Developing Software Using Vb Or Java • C++ Or Java: Which Way To Go? • Java Server Pages (jsp) Or Java Server Face(jsf Which Path To Trend? ? ? ? • 2 • 3 • 4
Are There Any Logical Programmers Here? Prolog Preffered • Help! Android Sdk Emulator Not Working • C Programming Training
