how do u read all doubles from txt file? - java

Its easy when have a file of all doubles, but when
there is a non-double somewhere in between,
i wouldnt be able to catch all of them.
For example:
604.2
609.2
6042
604.4
4234.324
312
gfsdgfreg
6043
604.3
The output:
604.2
609.2
6042.0
604.4
4234.324
312.0
Apparently, two doubles are missing. Is there a way
to catch all of them just by using hasNextDouble()?
Thx in advance if u dont get a reply. I saw somewhere
that I could parse each of them to double and catch the
exception, but i am really not that advanced
what i have here is:
import java.util.*;
import java.io.*;
public class Lab11{
public static void main(String[] args)
throws FileNotFoundException{
File nums = new File("file.txt");
int size = arrSize(nums);
double[] phoneNums = copy(nums,size);
for(int i=0;i<phoneNums.length;i++)
System.out.println(phoneNums[i]);
}
public static int arrSize(File f)
throws FileNotFoundException{
int arrSize = 0;
Scanner in = new Scanner(f);
while(in.hasNextDouble()){
arrSize++;
in.next();
}
in.close();
return arrSize;
}
public static double[] copy(File f,int size)
throws FileNotFoundException{
Scanner in = new Scanner(f);
double[] list = new double[size];
int i = 0;
while(in.hasNextDouble()){
list[i++] = in.nextDouble();
}
in.close();
return list;
}
}

I would give your two while loops the following structure:
while(in.hasNext()) {
if(in.hasNextDouble()) {
// your inner while loop code here
} else {
in.next();
}
}
Otherwise, you'll miss everything after the first instance of a non-double.

Since you are using
while(in.hasNextDouble()){
arrSize++;
in.next();
}
As soon as it reaches a non-double, it will stop, and won't proceed further.
You have to keep looping through every line in the while loop, and within this loop, use an if statement to check whether what you're reading is a double or not.

Like Takendarkk said, once a non-double is found in the input in.hasNextDouble() will evaluate to false, ending your loop.
Here is an example of a (hopefully) more simplified way of doing what you are doing:
// create a new list for our doubles
List<Double> doubles = new LinkedList<>();
try {
// open our doubles file reader
BufferedReader reader = Files.newBufferedReader(Paths.get("doubles.txt"), Charset.defaultCharset());
// read our doubles file
String line;
while ((line = reader.readLine()) != null) {
if (line.matches("^[0-9]*(\\.[0-9]+)?$")) {
doubles.add(Double.parseDouble(line));
}
}
// close our doubles file reader
reader.close();
} catch (IOException e) {
e.printStackTrace(); // for the sake of the example
}
// output our doubles
for (Double d : doubles) {
System.out.println("Double: " + d);
}
Hope this helps

Related

Find the avg of a set and the class using a text file in java

Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.
For example (the txt file would contain the following numbers)
4567687509
569563
the marks are:
45%, 67%, 68%, 75%, 9%
56%, 95%, 63%
Write a method that will calculate the average of each set of marks as well as the overall average.
Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.
import java.io.*;
public class ReadFile {
public static int calcAvg (String x) throws IOException {
int avg = 0;
int count = 0;
FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
BufferedReader br = new BufferedReader (fr);
while ((x = br.readLine()) != null) {
if (count <= 2) {
}
}
br.close();
return avg;
}
considering an input file like
45676875
09569563
first I will have a method to read the file and transform it into a better structure to use.
public List<Integer> readFile() throws FileNotFoundException {
List<Integer> numbers = new ArrayList<>();
String line = "";
try {
FileReader fr = new FileReader("src/main/resources/numbers.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
for (int i = 0; i <= line.length() - 2; i+=2) {
char[] chars = line.toCharArray();
int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
numbers.add(number);
}
}
} catch (Exception e) {
System.out.println(e);
}
return numbers;
}
then I will have the method to calculate the AVG
public float calcAvg(List<Integer> numbers) throws IOException {
int sum = 0;
for (int number: numbers){
sum+= number;
}
return sum/(numbers.size());
}
of course, you need a start method to make things happen
something like
public void init() throws IOException {
List<Integer> numbers = readFile();
float result = calcAvg(numbers);
System.out.println(result);
}
It's as easy as that. You practically want people to do stuff for you, but this is a question and answer site. Here you'll see some code for getting the individual percentages. You'll figure the rest out.
File f = new File(path);
try {
Scanner scanner = new Scanner(f);
String line = scanner.nextLine();
for (int i = 0; i < line.length() - 1; i+=2) {
double percentage = Double.parseDouble(line.substring(i, i+2)) / 100.0;
}
} catch (Exception e) {e.printStackTrace();}

Scanner for input file and storing data objects from input file in array

Basically, I had to create a scanner for a given file and read through the file (the name is input through the terminal by the user) once counting the number of lines in the file. Then after, I had to create an array of objects from the file, of the correct size (where the num of lines comes in). Then I had to create another scanner for the file and read through it again, storing it in the array I created. And lastly, had to return the array in the method.
My problem is I cannot seem to get the second scanner to actually store the file objects in the array.
I've tried using .nextLine inside a for loop that also calls the array, but it doesn't seem to be working.
public static Data[] getData(String filename) {
Scanner input = new Scanner(new File(filename));
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
System.out.println(count);
Data[] data = new Data[count];
Scanner input1 = new Scanner(new File(filename));
while (input1.hasNextLine()) {
for (int i = 0; i < count; i++) {
System.out.println(data[i].nextLine);
}
}
return data;
}
I expect the output to successfully read the input file so that it can be accessed by other methods that I have created (not shown).
You should definitely use an IDE if you don't have one, try intellij... There you have autocompletion and syntax checking and much more.
It is not clear what you want to do in your for loop, because there are several mistakes, for example the readline() function works only with the scanner objekt, so you can do input.nextline() or input1.nextline()`...
so I just show you, how you can get the Data from a file with Scanner:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Readfile {
public static void getData(String filename) throws FileNotFoundException {
ArrayList<String> test = new ArrayList<>(); //arraylist to store the data
Scanner inputSc = new Scanner(new File(filename)); //scanner of the file
while (inputSc.hasNextLine()) {
String str = inputSc.nextLine();
System.out.println(str); //print the line which was read from the file
test.add(str); //adds the line to the arraylist
//for you it would be something like data[i] = str; and i is a counter
}
inputSc.close();
}
public static void main(String[] args) {
try {
getData("/home/user/documents/bla.txt"); //path to file
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You don't need to read thru the file twice - just use an ArrayList to hold the data that's coming in from the file, like this, and then return Data[] at the end:
public static Data[] getData(String filename) {
List<Data> result = new ArrayList<>();
try (Scanner input = new Scanner(new File(filename))){
while (input.hasNextLine()) {
Data data = new Data(input.nextLine());
result.add(data);
}
}
return result.toArray(new Data[0]);
}
Not clear what Data.class do you mean, if you switch it to String, the problem obviously would be in this line
System.out.println(data[i].nextLine);
if you want to assign and print simultaneously write this
for (int i = 0; i < count; i++) {
data[i] = input1.next();
System.out.println(data[i]);
}
and dont forget to close your Scanners, better use try-with-resources.
If your Data is your custom class you'd better learn about Serialization-Deserialization
Or use some ObjectMapper-s(Jackson, for example) to store your class instances and restore them.
Your way of opening the file just to count the lines and then again looping through its lines to store them in the array is not that efficient, but it could be just a school assignment.
Try this:
public static Data[] getData(String filename) {
Scanner input = null;
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
int count = 0;
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println(count);
Data[] data = new Data[count];
try {
input = new Scanner(new File(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
for (int i = 0; i < count; i++) {
Data d = new Data(input.nextLine(), 0, 0);
data[i] = d;
System.out.println(data[i].name);
}
input.close();
return data;
}
After the 1st loop you must close the Scanner and reopen it so to start all over from the first line of the file.

Reading integers from text file

I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
The error I get is: NoSuchElementException.
The file looks like this:
N,X1,Y1,X2,Y2,X3,Y3
While n equals 3 in this example.
I call this method a in the main method like this:
readFromFile("file.txt");
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
where isNumeric can be defined as follows:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanneruses whitespace as the default delimiter. You can change that with useDelimiter See here: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Read from a file in Java

Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}
I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].
You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.
Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}
EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}
File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources