Read double from .txt file - java

I have a .txt file where data are written like this:
ZONEIDFROM;ZONEIDTO;DISTANCETYPE;FACILITYID;DISTANCE;
1;2;C;HF;9,416667;
I want to return the distance if zoneidfrom = 1 and zoneidto = 2.
Everything seems to be okay in my code except for the distance which is a double.
public void Load(String filename, int zoneidfrom, int zoneidto, String mode) throws Exception{
queue.clear();
int from,to;
double dist;
String c_or_l;
BufferedReader br = new BufferedReader(new FileReader(filename));
String ligne = br.readLine(); //First line read
while(ligne != null){
ligne = br.readLine(); //First line read
String [] tab = ligne.split(";");
ArrayList<Double> d = new ArrayList<>();
d.add(Double.parseDouble(ligne));
from = Integer.parseInt(tab[0]);
to = Integer.parseInt(tab[1]);
c_or_l = tab[2];
dist = d.get(4);
if(zoneidfrom == from && zoneidto == to && c_or_l.equals(mode));{
distance(dist);
}
}
}
public double distance(double db_distance){
return db_distance;
}

Firstly, your code is not parsing the correct string value for the double. You should be parsing tab[4], not the whole line.
Secondly, the double value contains a comma for the decimal separator. Double.parseDouble() does not take Locale into account.
You should use a NumberFormat to parse the double, while using an appropriate Locale.
See this answer for more details.

ligne is string and it will be "1;2;C;HF;9,416667;" in first while loop, now you are trying to parse it to double , obviously it will throw number format exception .
For distance to get you have to do, Double.parseDouble(tab[4].replace(",","."))

Related

Convert the retrieved float values from external file to an array of floats .So that it matches with the method

I have to get values from external file and write a float method for calculating the sum of numbers retrieved from the file
I was able to write the code for reading of file and it's working as i have tested it.I was also able to make the method for summation.The problem is i am unable to convert the vales of file as required by the method
public static void main(String[] args) throws IOException{
File file = new File("data.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
float values[]= new float[st]; // I tried this thing
}
}
// Method requires float values of file in an array
public static float naiveSum(float[] values) throws IOException {
float s = 0;
for(int i = 0; i < values.length; ++i)
s += values[i];
return s;
}
Excepted result is the sum of the numbers but nothing is in output as there is problem to convert the values as requested by the method
I expect, that you dont know how many numbers are in your file. So you should use a List to collect all the readed values, because instead of an array it has not a fixed size.
I also expect that all your float values are in seperate lines.
String st;
List<Float> valueList = new ArrayList<>();
while ((st = br.readLine()) != null) {
valueList.add(Float.parseFloat(st.trim()));
}
Float[] values = new Float[valueList.size()];
values = valueList.toArray(values);
So basically the code is reading the file line by line, removing whitespace from each line, then parsing it to Float and then putting it in the valueList. In the end the valueList is converted to an array, so you can pass it to your summarize function.

"java.lang.NumberFormatException: empty String" with a not empty String

I am currently working on a personal project outside of class and am running into some issues while reading in a text file into a linked list. When reading in the first double I get a
java.lang.NumberFormatException: empty String
error. I added a print line into the program to print out what I am trying to parse into a double and the variable is in fact, not empty, and is in fact a double.
Like I said above, I added a print line to print out the string I am trying to parse into a double and it seems to be okay. Here is the String that is read in and split into the array I am printing from:
500.0 % 04/05/2019 % This is paycheck 1 % true % 49.5
I have to parse two strings into doubles and I only run into problems with the first one. When I comment out the first double being parsed, the program runs with no problems. Here is the full output from running to program
*File loading*
*500.0*
*Exception in thread "main" java.lang.NumberFormatException: empty String*
*at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)*
*at sun.misc.FloatingDecimal.parseDouble(Unknown Source)*
*at java.lang.Double.parseDouble(Unknown Source)*
*at fileHandling.readPaycheck(fileHandling.java:194)*
*at UserMenu.main(UserMenu.java:20)*
The problems happens in the "Splitting the array into its appropriate temp variables" section in this line of code:
payCheckAmount = Double.parseDouble(tempArray[0]);
Here is the code for the method this is in
public void readPaycheck(LinkedList<PayCheck> paycheck) throws IOException {
// Declare Variables
Scanner sc = new Scanner(payChecks); // Scanner used to read in from the payChecks text file
String temp; // A string used to hold the data read in from the file temporarily
String[] tempArray; // A String array used to temporarily hold data from the text file
double payCheckAmount; // A double holding the amount of the paycheck
String paycheckDate; // A string holding the date of the paycheck
String description; // A string holding a description of the paycheck
boolean payCheckSplit; // A boolean stating if the paycheck has been split or not
double amountUnSplit; // A double
// A while loop that runs while the text file still has data in it
while (sc.hasNextLine()) {
// Reading in a new line from the paycheck file
temp = sc.nextLine();
// Splitting the line into an array
tempArray = temp.split(" % ");
// Temp output used for testing of the issue at hand
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
payCheckAmount = Double.parseDouble(tempArray[0]);
paycheckDate = tempArray[1];
description = tempArray[2];
payCheckSplit = Boolean.parseBoolean(tempArray[3]);
amountUnSplit = Double.parseDouble(tempArray[4]);
// putting the temp variables into a temp paycheck object
PayCheck tempCheck = new PayCheck(payCheckAmount, paycheckDate, description, payCheckSplit, amountUnSplit);
paycheck.add(tempCheck);
}
}
Edit:
Here is a Minimal, Complete, and Verifiable example of the problem I am running into:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws IOException {
// Declare Variables
File payChecks = new File("C:\\Users\\zwtw\\Documents\\paychecks.txt");
Scanner sc = new Scanner(payChecks);
while (sc.hasNextLine()) {
String temp = sc.nextLine();
String[] tempArray = temp.split(" % ");
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
double payCheckAmount = Double.parseDouble(tempArray[0]);
String paycheckDate = tempArray[1];
String description = tempArray[2];
boolean payCheckSplit = Boolean.parseBoolean(tempArray[3]);
double amountUnSplit = Double.parseDouble(tempArray[4]);
}
}
}
Here is the content of the text file mentioned in the code above:
500.0 % 04/05/2019 % This is paycheck 1 % true % 49.5
450.0 % 04/09/2019 % This is paycheck 2 % true % 49.75
Your text file likely contains empty lines. You can either remove the new lines in the text file, change how the text file is created, or just skip the empty lines when you read it.
This is how you skip the empty lines:
while (sc.hasNextLine()) {
String temp = sc.nextLine();
if (temp.equals("")) { continue; } // <--- notice this line
String[] tempArray = temp.split(" % ");
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
double payCheckAmount = Double.parseDouble(tempArray[0]);
String paycheckDate = tempArray[1];
String description = tempArray[2];
boolean payCheckSplit = Boolean.parseBoolean(tempArray[3]);
double amountUnSplit = Double.parseDouble(tempArray[4]);
}
}

Convert string to doubles in a .txt file?

I have a .txt file of numbers that are formatted like the following:
1.2 2.3 3.4 4.5
2.0 3.0 4.0 5.0
6.0 7.0 8.0 9.0
I'm trying to use a scanner to take each line as a string, convert each number to a double and then add them together to print to a new .txt file.
My error message looks like this:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "1.2 2.3 3.4 4.5" at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at
java.lang.Double.parseDouble(Double.java:538) at
scanstrings.ScanStrings.parseDouble(ScanStrings.java:51) at
scanstrings.ScanStrings.main(ScanStrings.java:33)
I was trying to use a split to separate each number so that they could be converted to doubles, but no matter what I do nothing seems to work, and I've found ways to split using spaces and periods but each way I try returns the same error message.
My code basically looks like this right now (I'm just starting so I'm sorry if it's just bad, I've also been messing with this for a while so some parts might just not make sense
//Construct Scanner object for the input file
Scanner input = new Scanner (new File("one.txt"));
//Construct Scanner object for the output file
PrintWriter output = new PrintWriter("result.txt");
//Read lines from the input file
while(input.hasNextLine()){
String line = input.nextLine();
String[] conv = line.split("\\s+");
String dub1 = conv[0];
String dub2 = conv[1];
String dub3 = conv[2];
String dub4 = conv[3];
//convert to double
double dub = parseDouble(line);
//compute sum
double total = 0;
if (dub != 0) //protect against division by zero
{
total += dub;
}
System.out.printf("\n", dub, total);
}
input.close();
output.close();
}
public static double parseDouble(String conv) throws NumberFormatException{
int i = 0;
while (!Character.isDigit(conv.charAt(i))) { i++; }
return Double.parseDouble(conv.substring(i).trim());
}
Welcome to StackOverflow!
You've split your line into individual terms, but then are passing the whole line to your parsing with this:
double dub = parseDouble(line);
Instead, try:
double dub = parseDouble(conv[0]);
for the first value. (You may even want to try creating a loop, for all values.)
(as far as i understood you wish to add the numbers in each line from input file, and print it on new line, in output file). An easier way would be to rely on Double.parseDouble(String) to convert the string to Double. New version of your parseDouble(line)
public static double parseDouble(String line){
double res = 0;
for(String number : line.split("\\s+") ){
try{
res += Double.parseDouble(number);
}
catch(NumberFormatException ex){
System.out.println("Cannot convert " + number + " to double");
}
finally{
return res;
}
}
So in that case, you should rename your parseDouble(String line) to getSum(String line)

Trouble with importing files

ZIPCODE, CITY, STATE, LATITUDE, LONGITUDE
ZIPCODE, CITY, STATE, LATITUDE, LONGITUDE
I'm trying to make this able to open a text file with addresses formatted as such, Create a loop that instantiates a new ZipCode object with the five perameters in order, and then adds that object to ArrayList myZips.
I have a feeling that at least my delimiters are wrong.
public void readZipCodeData(String filename){
Scanner inFS = null;
FileInputStream fileByteStream = null;
try{
// open the File and set delimiters
fileByteStream = new FileInputStream(filename);
inFS = new Scanner(fileByteStream);
inFS.useDelimiter(", *");
// continue while there is more data to read
while(inFS.hasNext()) {
// read five data elements
int zipCode = inFS.nextInt();
String city = inFS.next();
String state = inFS.next();
double latitude = inFS.nextDouble();
double longitude = inFS.nextDouble();
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);
}
fileByteStream.close();
// Could not find file
}catch(FileNotFoundException error1) {
System.out.println("Failed to read the data file: " + filename);
// error while reading the file
}catch(IOException error2) {
System.out.println("Oops! Error related to: " + filename);
}
}
Everytime I try running it as is it gives me a
java.util.InputMismatchException:
null (in java.util.Scanner) error on the double longitude line. Any ideas?
I'm not familiar with Scanner for input, but rather BufferedReader. I find it simple to use, and I hope this solution works for you:
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(filename, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
// THIS IS THE CODE FOR EVERY LINE
String[] data = line.split(", ");
int zipCode = Integer.parseInt(data[0]);
String city = data[1];
String state = data[2];
double latitude = Double.parseDouble(data[3]);
double longitude = Double.parseDouble(data[4]);
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
} catch (NumberFormatException x) {
System.err.format("NumberFormatException: %s%n", x);
}
In this example, I read a whole line with BufferedReader.readLine(), and manually parse it using String.split() and Integer.parseInt() / Double.parseDouble(). It's more intuitive, and it works!
See working example here.
Because of the comment below, I guess I cannot suggest the answer above. However, there are two potential problems I see:
You might have not put in a double in the input file. Simple, honest mistake.
Or, by this SO answer, your locale may be set wrong. In some places, they use a , for decimal point instead of . Try switching these around.
Try something like this. Instead of parsing one field at a time, grab the whole line, turn it into an array of String using your delimiter , then parse to int/double. Scanner.nextLine() grabs the whole line for you.
try{
// open the File and set delimiters
fileByteStream = new FileInputStream(filename);
inFS = new Scanner(fileByteStream);
// read five data elements
String[] data = inFS.nextLine().split(", ");
int zipCode = Integer.parseInt(data[0]);
String city = data[1];
String state = data[2];
double latitude = Double.parseDouble(data[3]);
double longitude = Double.parseDouble(data[4]);
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);

Java parse a Sting with letters and numbers for an Integer

I'm working with data that is a String followed by spaces and then a numeric value.
ncols 10812
nrows 10812
xllcorner -107.0005555556
yllcorner 36.99944444444
cellsize 9.2592592593e-05
I'm trying to just read in just the numeric value. I know that from going to String to Integer or Double I can use the standard type conversions.
Integer.valueOf(stringOfInteger);
Double.valueOf(stringOfDouble);
In order to get just the numeric value I tried this as a test:
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine();
line.replace("[a-z]","");
line.replace(" ","");
System.out.println(line);
and it output ncols 10812
I'm also worried about reading the cellsize value as it has an exponential.
You can do this for each line:
...
String[] fields = line.split("\\s+");
String name = fields[0];
float value = Float.parseFloat(fields[1]);
...
This code will split each line in fields using the spaces as a separator. The first field is a String so you can use it directly (or ignore it). The second one is a Float value so you have to convert it before using it. You can use Double if you prefer.
Try this one
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
// split each line based on spaces
String[] words = line.split("\\s+");
//first word is name
String name = words[0];
// next word is actual number
Double value = Double.valueOf(words[1]);
System.out.println(name + ":" + value);
}
// don't forget to close the stream
br.close();
Output:
ncols:10812.0
nrows:10812.0
xllcorner:-107.0005555556
yllcorner:36.99944444444
cellsize:9.2592592593E-5
If all you want all the numeric values do a split on the space and the second item will contain your numeric value. Then you can do any conversions as needed and not have to worry about removing any exponents.
String[] data = new line.split(" ");
//remove all the spaces from the second array for your data
data[1] = data[1].replaceAll("\\s", "");
//parse to whatever you need data[1] to be
You could use the split function in Java as follows:
String [] dataArr = data.split("[ \t]+"); //assumes #data is you data string variable name
The dataArr, then, will look like this:
dataArr[0] = "ncols"
dataArr[1] = "10812"
dataArr[2] = "nrows"
dataArr[3] = "10812"
.
.
.
dataArr[n - 1] = "9.2592592593e-05" // #n is the size of the array
You could, then, use the Integer.parseInt(String str) to parse your numerical data into integers.

Categories

Resources