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)
Related
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]);
}
}
I've got the following code which reads my text file and gets the value inside the parentheses.
String content = new Scanner(new File(hello.txt)).useDelimiter("\\Z").next();
double value = Double.parseDouble(content.substring(content.indexOf("(") + 1, content.indexOf(")")));
System.out.println(value);
How can I change it so if the text file has multiple parentheses, it prints them all?
A sample text file would look something like this:
334.43 (0.03037)
655.32 (1.203)
734234.5948 (232.4358)
78764.342 (564.342342)
So I want the output to be:
0.03037
1.203
232.4358
564.342342
Use a loop and read the file line by line
Scanner sc = new Scanner(new File(hello.txt)).useDelimiter("\\Z");
while (sc.hasNextLine()) {
String content = sc.nextLine();
double value = Double.parseDouble(content.substring(content.indexOf("(") + 1, content.indexOf(")")));
System.out.println(value);
}
This question already has an answer here:
Input mismatch when reading double from file
(1 answer)
Closed 6 years ago.
I am trying to read from a CSV file using the Scanner but I am getting an InputMismatchException when I try and read the last double and are there is more than one line in my CSV file. I think this is because it is reading \n as part of the double. How do I get it to ignore the line break?
CSV file
P1,25,30
P2,10,10
Java
public static ArrayList<MarkEntry> readCSV(File file) {
ArrayList<MarkEntry> entries = new ArrayList<>();
try
{
Scanner in = new Scanner(file).useDelimiter(",");
while (in.hasNext())
{
String title = in.next();
double mark = in.nextDouble();
double outOf = in.nextDouble(); //Program Crashes here
entries.add(new MarkEntry(title, mark, outOf));
}
} catch (FileNotFoundException e)
{
System.out.println("File: " + file + " not found");
}
return entries;
}
You can use multiple delimeters:
Scanner in = new Scanner(input).useDelimiter(",|\\r\\n");
Note: On Linux, the line ending is just \n, so you would use this code:
Scanner in = new Scanner(input).useDelimiter(",|\\n");
The error is caused by the fact that your scanner tries to read up to the next delimiter (,) or to the end of the string. The last token will include the newline, and converting that value to a double results in the error you see.
Trim the newline off before parsing with your scanner:
String input = "foo,bar,2.5\n";
Scanner in = new Scanner(input.trim()).useDelimiter(",");
System.out.println(in.next());
System.out.println(in.next());
System.out.println(in.nextDouble());
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(",","."))
I'm currently trying to read a file from my HDD. The file name is "Sample.txt", below is my code. I'm able to get it to compile and run, but receive this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Proj1GradesService.errorReport(Proj1GradesService.java:42)
at Proj1GradesClient.main(Proj1GradesClient.java:13)
I've tried reading the file w/just a While loop and now with a try/catch, but received the same error, and I'm unsure what's exactly wrong with it. I'm trying to read the file from the Service Class and have the call to the method errorReport() from the Client Class.
Any help would be greatly appreciated.
import java.util.*; //allows use of Scanner class
import java.io.*; //for File and IOException classes
class Proj1GradesService
{ //begin Proj1GradesService
public void pageAndColHeading(char letter) //accepts char as a parameter
{ //start pageAndColHeading
switch (letter)
{ //start switch
case 'e': //write the caption for error report
System.out.println ("Error Report - Students With Invalid GPA"); //prints Error Report
break;
case 'v': //write the caption for valid report
System.out.println ("Valid Report - Students With Valid"); //prints Valid Report
break;
default: ; //do nothing
}//end switch
} //end pageAndColHeading
public void errorReport() throws IOException
{ //start errorReport
Scanner scanFile = null;
try
{
scanFile = new Scanner (new File ("p1SampleGPAData.txt"));
}
catch (FileNotFoundException fnfe)
{
System.out.println ("wrong file name.");
}
String name; //name read from file
double gpa; //gpa read from file
int count = 0; //line #
while (scanFile.hasNext( ))
{
name = scanFile.next();
gpa = scanFile.nextDouble();
System.out.println ("Line Number: " + count + "Name: " + name + "GPA: " + gpa);
++count;
} //end while
scanFile.close();
} //end errorReport
} //end class
Considering your file structure below which is assumed from printing statement
name1 1.1
name2 2.2
name3 3.3
Now according to your code following line
// consume your whole line. ie name1 1.1
name = scanFile.next();
// looking for double but instead getting string ie name2
// hence throwing InputMismatchException
gpa = scanFile.nextDouble();
Now to resolve above issue. You can use String.split().
// collect whole line
name = scanFile.next();
// split by one or more whitespace OR use your delimiter
String[] str = name.split("\\s+");
// gives name
String actName = str[0];
// gives gpa, throws NumberFormatException if str[1] is not double value
double gpa = Double.parseDouble(str[1]);
I hope this helps. If you need anymore help just ask.
Generally, InputMismatchException is thrown if the thing you're trying to parse doesn't match the format that Scanner expects.
So in this case, check your input file to see if the element you're parsing is actually a double. Be careful too of any extra whitespace.
This is most likely an issue of your data not matching what your program actually expects.
You need to recheck your file structure.
As the stacktrace shows nextDouble, the problem is a non-double within the file where scanner is expecing a double.
Without knowing what your input file looks like, this error is happening because you are trying to read character data into a double, and those characters being read are not doubles.
Make sure all the data you are reading in is in the format you expect it to be.
If this was me, I would read the entire data into a string, and then try to convert those strings in doubles, so I could surround that statement in a try/catch and then deal with it appropriately.