InputMismatchException with Scanner when reading double from string with \n—Java [duplicate] - java

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());

Related

Reading Text File into Array using Java generates Exception

Even though the file Movie_db.txt isn't empty, I get the following exception:
the text file consists of this:
hank horror 20.0 18 1
public void syncDB(List<Movie> movieList) throws IOException {
Scanner scanner = new Scanner("Movie_db.txt");
BufferedReader reader = null;
try {
String line = null;
String title;
String genre;
double movieDuration;
int ageRestriction;
int id;
while (scanner.hasNext()) {
title = scanner.next();
genre = scanner.next();
movieDuration = scanner.nextDouble();
ageRestriction = scanner.nextInt();
id = scanner.nextInt();
movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
}
} catch (Exception e) {
System.out.println("List is empty");
}
}
Considering your path is correct, there is a problem in your code. I'd change this line
Scanner scan = new Scanner("Movie_db.txt");
with this one
Scanner scan = new Scanner(Paths.get("Movie_db.txt"));
The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.
Read Scanner documentation for more info
genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.
You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.
Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));
Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.

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)

Why doesn't my program recognize the last names properly?

The scanner reads the wrong data, the text file format is:
111,Smith,Sam, 40,10.50
330,Jones,Jennifer,30,10.00
The program is:
public class P3 {
public static void main(String[] args) {
String file=args[0];
File fileName = new File(file);
try {
Scanner sc = new Scanner(fileName).useDelimiter(", ");
while (sc.hasNextLine()) {
if (sc.hasNextInt( ) ){ int id = sc.nextInt();}
String lastName = sc.next();
String firstName = sc.next();
if (sc.hasNextInt( ) ){ int hours = sc.nextInt(); }
if (sc.hasNextFloat()){ float payRate=sc.nextFloat(); }
System.out.println(firstName);
}
sc.close();
} catch(FileNotFoundException e) {
System.out.println("Can't open file "
+ fileName + " ");
}
}
}
The output is:
40,10.50
330,Jones,Jennifer,30,10.00
It is supposed to be:
Sam
Jennifer
How do I fix it?
The problem is that your data isn't just delimited by commas. It is also delimited by line-endings, and also by Unicode character U+FF0C (FULLWIDTH COMMA).
I took your code, replaced the line
Scanner sc = new Scanner(fileName).useDelimiter(", ");
with
Scanner sc = new Scanner(fileName, "UTF-8").useDelimiter(", |\r\n|\n|\uff0c");
and then ran it. It produced the output it was supposed to.
The text , |\r\n|\n|\uff0c is a regular expression that matches either:
a comma followed by a space,
a carriage-return (\r) followed by a newline (\n),
a newline on its own,
a Unicode full-width comma (\uff0c).
These are the characters we want to delimit the text by. I've specified both types of line-ending as I'm not sure which line-endings your file uses.
I've also set the scanner to use the UTF-8 encoding when reading from the file. I don't know whether that will make a difference for you, but on my system UTF-8 isn't the default encoding so I needed to specify it.
First, please swap fileName and file. Next, I suggest you use a try-with-resources. Your variables need to be at a common scope if you intend to use them. Finally, when using hasNextLine() I would then call nextLine and you can split on optional white space and comma. That could look something like
String fileName = // ...
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] arr = line.split("\\s*,\\s*");
int id = Integer.parseInt(arr[0]);
String lastName = arr[1];
String firstName = arr[2];
int hours = Integer.parseInt(arr[3]);
float payRate = Float.parseFloat(arr[4]);
System.out.println(firstName);
}
} catch (FileNotFoundException e) {
System.out.println("Can't open file " + fileName + " ");
e.printStackTrace();
}

Why I get the java.lang.NullPointerException? [duplicate]

This question already has answers here:
System.console() returns null
(13 answers)
Closed 7 years ago.
I want to input a name and to print the first char ....
public class Test {
public static void main(String[] args) {
Console console = System.console();
System.out.println("Type your name : ");
String inputChar = console.readLine();
char firstChar = inputChar.charAt(0);
System.out.println(firstChar);
}
}
Some IDEs will return NPE for Console class. you can use the Scanner class and do it easily:
try this:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Name:");
String s = scan.next();
System.out.println(s.charAt(0));
this will print the first letter of your input String.
Using the Console class can a bit unreliable at times.
For reading console input, it would be preferrable to use either the Scanner class or a BufferedReader.
You can use a Scanner like :
Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);
You can also use BufferedReader like :
pre Java 7 syntax
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
Java 7 syntax
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
System.out.print("Enter text : ");
String input = br.readLine();
System.out.println(input);
} catch (Exception e) {
e.printStackTrace();
}
Note: You need to use a try-catch statement when calling br.readLine() because it throws an IOException.
You can use Scanner if you want to read tokens (chunks of text separated by spaces). Use a BufferedReader if you want to simply read from the InputStream.

Reading text file into Java array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}
Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}
First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int

Categories

Resources