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
Related
I'm working on a school programming lab and I've gotten stuck. The book is not too helpful in teaching how to format I/O properly, or at least I'm not understanding it properly. I need a bit of help getting on with the next steps, but here's the full requirements of the program I'm supposed to be making:
A hotel salesperson enters sales in a text file. Each line contains
the following, separated by semicolons: The name of the client, the
service sold (such as Dinner, Conference, Lodging, and so on), the
amount of the sale, and the date of that event. Write a program that
reads such a file and displays the total amount for each service
category. Display an error if the file does not exist or the format is
incorrect. In addition to the program specifications listed, your
program should both print the results as well assend the results to a
separate output file.
Example of input.txt:
Elmer Fudd;Lodging;92.00;11-01-2014
Elmer Fudd;Conference;250.00;11-02-2014
Daffy Duck;Dinner;19.89;11-02-2014
Daffy Duck;Conference;275.00;11-02-2014
Mickey Mouse;Dinner;22.50;11-02-2014
Mickey Mouse;Conference;275.00;11-02-2014
I'm currently stuck on figuring out how to get the file properly loaded and formatted, which I think I did right, but then my professor suggested breaking each into it's own line, but nowhere in my book does it clearly tell how to do that. Just to be clear, I'm not looking for a coding miracle, I just would like someone to help guide me in the right direction as to what I should do next. Possibly a better way to handle this situation in a nicely detailed guide? Nothing fancy though. Thank you in advance, and here's my current code.
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
Scanner lineScanner = new Scanner(inputFile);
lineScanner.useDelimiter(";");
while (lineScanner.hasNext())
{
String line = in.nextLine(); //Here's where I'm really stuck
System.out.print(line); //Not to say I'm not stumped all over.
}
in.close();
out.close();
lineScanner.close();
}
}
From what Jason said, I'm at this now:
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
while (in.hasNext())
{
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}
}
in.close();
out.close();
}
}
Stick to one scanner.
Read each line in total, rather than breaking on the ';'.
Then use String.split() to break the line of text apart at the ';' separator.
Then check the second part (zero based index) to retrieve the service category and add the value in the third part to the relevant total.
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}
I'm utterly lost in Arrays and need help...Here is the end objective of this program....
In a file called AccountArray.java, write a client program (your main method) that reads from the file called customers.txt. Read the first number in the file and create an
array of Account objects, with that number of elements. Use a “for” loop to create an Account object for each line of information you read from the file and store that into an element of the array
Here's where I am at so far... my main concern is the FileNotFound Exception Error.... I have a file named customers.txt saved in the program folder but do I need to initialize it somehow or something?
Any other input regarding things I am doing wrong in this program would be greatly accepted, I'm just beginning to learn this stuff.
public class AccountArray {
/**
* #param args
*/
public static void main(String[] args) {
List<Account> accountsArray = new ArrayList <Account>();
String name, accountnumber, balance;
Scanner diskScanner = new Scanner(new File("customers.txt"));
Scanner scanner= new Scanner ("customers.txt");
scanner.useDelimiter(" ");
int objects= scanner.nextInt();
Account[] accounts=new Account[objects];
while (objects>0){
name = scanner.nextLine();
accountnumber = scanner.nextLine();
balance = scanner.nextLine();
for(int i = 1; i < objects; i++) {
accountsArray.add(new Account(i, name, accountnumber, balance));
}
objects=objects-1;
System.out.println(name+ " " + accountnumber + " " + balance +"\n"); }// just for debugging
}
}
sample of file :
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
Well, first of all, you're using the wrong Scanner object:
Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful
To fix the FileNotFound Exception, you need to move the file customers.txt to the folder that is output by new File("customers.txt").getAbsoultePath(); as suggested by Freaky Thommi.
You will also run into a few other errors further down, but I'll let you figure those out on your own...
Is this run form eclipse. If yes you need to have this file under your project root folder. You can always find out the absolute path by using
new File("customers.txt").getAbsoultePath();
Print this to console and see if file is present at this location
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.
I'm currently writing this program that I require to read info from a text file and to then compare the info read to a user input and output a message saying if it was a match or not.
Currently have this. The program is sucessfully reading the data specified but I can't seem to compare the strings correctly at the end and print a result.
Code is below any help would be greatly appreciated.
import java.util.Scanner; // Required for the scanner
import java.io.File; // Needed for File and IOException
import java.io.FileNotFoundException; //Required for exception throw
// add more imports as needed
/**
* A starter to the country data problem.
*
* #author phi
* #version starter
*/
public class Capitals
{
public static void main(String[] args) throws FileNotFoundException // Throws Clause Added
{
// ask the user for the search string
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter part of the country name: ");
String searchString = keyboard.next().toLowerCase();
// open the data file
File file = new File("CountryData.csv");
// create a scanner from the file
Scanner inputFile = new Scanner (file);
// set up the scanner to use "," as the delimiter
inputFile.useDelimiter("[\\r,]");
// While there is another line to read.
while(inputFile.hasNext())
{
// read the 3 parts of the line
String country = inputFile.next(); //Read country
String capital = inputFile.next(); //Read capital
String population = inputFile.next(); //Read Population
//Check if user input is a match and if true print out info.
if(searchString.equals(country))
{
System.out.println("Yay!");
}
else
{
System.out.println("Fail!");
}
}
// be polite and close the file
inputFile.close();
}
}
You should try reading the input from a textField in an user interface(visible window) where the user puts the country and getting that as raw input shortens the code.(Only if you have a visible window on screen)
I don't have that good experience with scanners, because they tend to crash my applications when I use them. But my code for the same test does only include a scanner for the file which does not crash my application and looks like following:
Scanner inputFile = new Scanner(new File(file));
inputFile.useDelimiter("[\\r,]");
while (inputFile.hasNext()) {
String unknown = inputFile.next();
if (search.equals(unknown)) {
System.out.println("Yay!");
}
}
inputFile.close();
I think the easiest way to compare string against a file is to add a visible window where the user types the country, and reading the input to a string with String str = textField.getText();
I am guessing that your comparison is failing due to case-sensitivity.
Should your string comparison not be CASE-INSENSITIVE?
There are a few possible issues here. First, you're converting the searchString to lower case. Are the data in the CSV also lower case? If not, try using equalsIgnoreCase instead. Also, it seems to me like you should be able to match parts of the country name. In that case, equals (or equalsIgnoreCase) would only work if the user inputs the complete country name. If you want to be able to match only a part, use contains instead.
Looking for help with the following code...
package pkgPeople;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class CreateWithoutSerialization {
public static void main(String[] args) throws Exception
{
BankAccount bankAccount = new BankAccount(0, 0);
Person person = new Person();
String nm;
int ht;
int wt;
long ba;
double bal;
File inFile = new File("G:/CS9.27/inperson.txt");
File outFile = new File("G:/CS9.27/outperson.txt");
PrintWriter writer = new PrintWriter(outFile);
Scanner reader = new Scanner(inFile);
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
person.setName(nm);
person.setHeight(ht);
person.setWeight(wt);
bankAccount.setAcctID(ba);
bankAccount.setBalance(bal);
System.out.println(person.toString());
//Write the attributes in ASCII to a file
writer.printf("%s is the name of the person.\r\n",nm);
writer.printf("%d inches is the height of %s.\r\n",ht, nm);
writer.printf("%d pounds is the weight of %s\r\n",wt,nm);
writer.printf("%d dollars is the balance of %s\r\n", bal, nm);
writer.printf("%l is the ID of the bank account.\r\n", ba);
}
}
Upon running, i get this exception..
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at pkgPeople.CreateWithoutSerialization.main(CreateWithoutSerialization.java:23)
Is this a file error? Have tried multiple fixes but still stuck.
The exception is being thrown in the call to reader.nextLine() According to the javadoc, this means that nextLine() could not find a next line.
Based on a careful reading of the javadoc, I think that this means that your input file is empty. You could test this by calling hasNextLine() before the call to nextLine().
As a beginner in a programming language, you need to learn how to use the documentation and resources made readily available for that language.
If you look at the javadoc for the method you are using here you would soon realize that the problem is that there is not a new line character for the Scanner to read in a line. Check your input file and make sure it meets the specifications. If you are sure your input file is correct you can do some debugging by using the file API to make sure the input File exists before attempting to use it as input for the Scanner.
All of the information you need is readily available in the javadoc.
Hmmm... I there are two things which are missing here....
Now the NoSuchElementException comes when input is exhausted . It need not to be related to nextLine(). So check whether for the following number of reads
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
You have equal number of lines in your inperson.txt
Also
When done writing ... do this also..
writer.flush();
writer.close();
Otherwise you won't see any output file... :)
good luck