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.
Related
I am still new to java and my assignment for school this week has me at a loss at the moment. Here is the assignment: Your assignment is to read the student.dat data file. First, review the attached program called
Warning.java file. The program reads a file of student academic credit data. Each line of the
input file will contain the student name (a single String with no spaces), the number of
semester hours earned (an integer), and the total quality points earned (a double).
Using the Warning.java file as the starter code for this assignment, add the following:
Add the code to calculate the gpa.
Display the name if the gpa is less than 2.0.
Test to ensure the output is accurate.
Add code to catch the following exceptions:
• A FileNotFoundException if the input file does not exist.
• A NumberFormatException if it can’t parse an int or double when it tries to – this
indicates an error in the input file format. Display the record number in error.
So the warning.java file I was given has comments in it about where our code should go and that is what is confusing me. Here is the code I have so far:
enter code here:
// Warning.java Java Foundations
//
// Reads student data from a text file and writes data to another text file.
// ****************************************************************************
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class warning
{
public static void main (String[] args)throws IOException
{
int creditHrs = 0; // number of semester hours earned
double qualityPts = 0; // number of quality points earned
double gpa = 0; // grade point (quality point) average
String name = null;
grade report = new grade(); //I created a class called but I feel it is unnecessary.
// Set up scanner to input file
Scanner inFile = new Scanner(new
File("C:\\Users\\patti\\Desktop\\Patricksdcom101class\\CSIT 210\\students.dat"));
System.out.println ("\n Students on Academic Warning:\n");
// Process the input file, one token at a time
while (inFile.hasNext())
{
// Get the credit hours and quality points and
// determine if the student is on warning. If so,
// display the student's name.
Scanner scan = new Scanner(System.in);
name = inFile.next();
creditHrs = Integer.parseInt(inFile.next());
qualityPts = Double.parseDouble(inFile.next());
// Insert gpa calculation
// and statement to determine if the student name is listed.
gpa = qualityPts/creditHrs;
if (gpa < 2.0) {
gpa = qualityPts/creditHrs;
DecimalFormat df = new DecimalFormat("0.###");
System.out.println(name +"\t" + df.format(gpa));
}
}
inFile.close();
//insert catch statements
try {
File file = new File("g:\\students.dat");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException x) {
System.out.println();
System.out.printf("Invalid, file does not exist please try again");
}
catch (Exception x) {
x.printStackTrace();
}
}
}
I am trying to get the number format exception to work for me, I have the file not found exception there but I feel like I did it wrong. The comment section that says: "Get the credit hours and quality points and determine if the student is on warning. If so, display the student's name." What I can't figure out is when I put anything in that while loop like a system.out.println statement, the ouput loops that string along with the information from the file. The instructions make it sound like I am suppose to take user input for the credit hours and quality points right? I would be eternally grateful to all of you if you can assist me in making my program come together.
Thank You and Have a Marvelous Day,
Patrick
I cannot explain my problem very well, this is the prompt.
I believe I am going in the right direction, my professor really went through this fast. Even though I am using the book and asking for help, it is to no avail.
'**Ask the user to enter a filename on the keyboard, including “.txt.” Read five integers from that file (all on the same line, separated by spaces) and tell the user their sum by printing it to the screen (console).**'
It compiles and runs, but when entering the filename(io.txt) I get an Exception in thread "main" java.util.NoSuchElementException: No line found
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String myString = " ";
Scanner inputStream = null;
System.out.println("Please enter a Filename, including '.txt' at the end: ");
myString = in.next();
try
{
inputStream = new Scanner(new FileInputStream(myString));
}
catch(FileNotFoundException e) //Giving the file not found a name,
{
System.out.println("Invalid File or filename");
System.out.println("Or could not be found,try again");
System.exit(0);
}
//True will always add on, not overwrite
int n1 = inputStream.nextInt();
int n2 = inputStream.nextInt();
int n3 = inputStream.nextInt();
int n4 = inputStream.nextInt();
int n5 = inputStream.nextInt();
String line = inputStream.nextLine(); //wait for new line, get the next line
inputStream.close( );
System.out.println("The five numbers read from the file are: ");
System.out.println(n1+" , "+ n2 + ", "+ n3 + ", "+ n4 +", "+ n5);
System.out.println("Which adds together to eqaul: " + (n1+n2+n3+n4+n5));
}
I want direction, not for someone to solve it for me.
After testing the code you gave it returns with
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.example.Test.main(Test.java:37)
which is the following line in your code
String line = inputStream.nextLine(); //wait for new line, get the next line
So your code tries to read another line from the file, but it can't find one. In reality what this means is your code is expecting to read
"1 2 3 4 5\n" from a file io.txt whereas the file actually contains "1 2 3 4 5" (no newline at the end of the file).
However since you've already read all the integers you needed you can simply stop there.
Also make sure to close your file stream.
Use in. nextLine() in place of in. next().
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)
I am writing a program thats supposed to read a simple text file and output a list of all the letters in that .txt file, ordered with the most frequently used letter to the least frequently used letter.
I have finished coding a working Java program that asks for file name and outputs the text within the file. But I am unsure how to go about outputting a list of the letters. What I am not sure specifically is what methods(if any) within the reader class I could use that reads in each letter in the .txt file. Any help would be appreciated!
This is current code:
// Here I import the Bufered Reader and file reader Libraries
// The Buffered Reader library is similar to Scanner Library and
// is used here to read from a text file. File reader will allow
// the program to access windows file system, get the text file
// and allow the Buufered Reader to read it in.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class TextFileReaderApp
{
// I added "throws exception" in case there is an an error in the
// main method, throw an exception, so it can prevent further
// errors from occuring if java doesnt know the main methods going
// to throw an error.
public static void main(String[] args) throws Exception
{
// below I diplay a welcome messgae to the user
System.out.println();
System.out.println("Welcome to the Text File Reader application!");
System.out.println();
// Below I create an instance of the Scanner class to get
// input from the user.
Scanner userInput = new Scanner(System.in);
String selection = "y"; //this is the string variable that's used in
//the while loop to continue the program.
// Below I created a while loop that continues the program if the user
// keeps selecting y as their selecion
while (selection.equalsIgnoreCase("y"))
{
// this line of code is supposed to ask the user for text file name under
// the C:/ directory and must not be hidden in any foler.
System.out.print("Please enter the name of the .txt file: C/");
FileReader file = new FileReader("C:/" + userInput.next());
// file object is used as a parameter in buffered reader.
BufferedReader textReader = new BufferedReader(file);
// below I create and initialize an object of type string called text that will
// store whats inside of the text file.
String text = "";
// I use the readLine statement to read line after line of the text.
// Once it has read everything it will return null.
String lineText = textReader.readLine();
// code below is a test for me to see if the code above works and is able to read
// the text inside the file and output it.
while(lineText != null)
{
// this reads the text line for line and ads it to the text variable for output.
text = text + lineText + "\n";
lineText = textReader.readLine();
}
System.out.println(text);
}
// These 3 code lines ask the user if he/she would like to continue with the program.
System.out.println();
System.out.print("Continue using the Text File Reader? (y/n): ");
choice = user_input.next();
System.out.println();
}
}
If you need to count letters / characters you can do it just as well on lines / words etc. No need to involve the Reader here.
for (char c : someString.toCharArray ()) {
// handle the character
}
Should work once you have any String from your file.
This reads all characters from textReader until EOF is reached or an exception occurs.
try {
for(int i = textReader.read(); i != -1 /* EOF */; i = textReader.read()) {
char c = (char) i;
// do whatever you want with your char here
}
} catch(IOException)
textReader.close();
first of all you might want to use a StringBuilder instead of your String text because of alot better performance.
"text = text + lineText" will create another String object every time it is executed, StringBuilder works better in this case).
One way to achieve what you want is to read character for character of your textLine and use a switchcase block with all letters and add them to an array containing integers when they occur. Example:
int[] array = new int[26];
switch(character){
case "a":
array[0] += 1;
break;
case "b":
array[1] += 1;
break;
//....
}
and so on...
in the end you use a simple for loop and print the values of your array. Now you see how many times you have entered which character.
I have a scanner called input with this code:
Scanner input = new Scanner(System.in);
int cFreq = 0;
System.out
.println("Enter the symbol which you want to find the frequency of:");
char s = 'a';
symbolLoop: while (s == 'a') {
try {
s = input.next(".").toLowerCase().charAt(0);
} catch (InputMismatchException e) {
System.out.println("Please enter a valid symbol!");
input.next();
}
switch (checkSymbol(s)) {
case 0:
s = 'a';
break;
case 1:
break symbolLoop;
}
}
for (int i = 0; i < words.size(); i++) {
cFreq += words.get(i).find(s, true);
}
System.out.println("Number of times " + s + " is in the coded words: "
+ cFreq);
}
However when it reaches the line where it reads from the scanner it terminates with this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.next(Scanner.java:1418)
at Home.frequency(Home.java:118)
at Menu.select(Menu.java:58)
at Menu.view(Menu.java:17)
at Home.main(Home.java:22)
(Home is the name of the class).
I have no idea what is causing this and would appreciate some help! :)
Thanks!
EDIT:
I have also tried with this code: String str = input.nextLine(); in the same method but it throws the same error.
If data from user wouldn't match "." regex (possibly surrounded by delimiters - whitespaces) next(".") would't throw NoSuchElementException, not InputMismatchException.
NoSuchElementException exception is thrown when Scanner can't even hope for more data, in which case it is sure that potentially next element will not even exist. Such situation is only possible if Scanner knows that source of data will not have more elements, which in case of Stream is when we will read entire content of stream (like in case of FileInputStream) or it will be closed.
In case of System.in we can assume that content of this stream is infinite, because it is provided by user, so when we try to read from it, application is waiting until user will provide its data. Which means that only way Scanner would throw NoSuchElementException is when System.in was closed, so next doesn't have more data to read.
To avoid such cases you should avoid closing streams which are using System.in because you will not be able to reopen it again in your application.