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
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 am working on a simple program that takes input from user and then saves it with specific file name.
To be more precise:
public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;
public static void main(String[] args) throws IOException {
System.out.print("File name: ");
name = in.nextLine();
fw = new FileWriter(name + ".txt", false);
System.out.println("Continue typing/type save to quit");
while(!quit) {
String word = in.nextLine();
if(word.equals("save")) {
fw.close();
quit = true;
}
else {
fw.write(word + "\n");
}
}
Program asks for file name.
User is typing words until he types "save" which saves the file
As you can see program ask user for file name at the beginning, before he starts to type. This is my problem. I want my program to ask the user for a file name at the end, after he typed all words. Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.
I would like to know is there any solution to my problem or what kind of information should I look for.
You have two options:
Store all the user input in memory (in a List<String> for instance) and then write out the words after seeing the save keyword and getting the output filename from the user.
Open the output file as you are doing, but with a temporary name, and write the words as you read them. Upon seeing the save keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.
Unless you need to process millions of words I'd go with option 1 for its simplicity.
I have a basic User Input and System Output program using strings, and at the start of the program it asks for the user's name, which it saves as a string variable inside the program.
Scanner input = new Scanner(System.in);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
What I want is for the program to save all new names it receives in an external file (like a
text file), and whenever a name is input it checks to see if it has encountered that name before. I want to use an if / else statement to have it display a different output depending on whether or not it has seen that name before. How do I go about accomplishing this?
~
My apologies if this is a basic problem (or if it has been answered before), but I am relatively new to java and I wasn't able to find a solution. Thank you for your help! ^-^
I think this program may accomplished your requirement
public static void main(String as[]) throws Exception{
int i=0;
File f1=new File("D:\\Name.txt");
FileWriter fw=new FileWriter(f1,true);
Scanner input = new Scanner(System.in);
Scanner output=new Scanner(f1);
System.out.println("Hello there! What's your name?");
String name = input.nextLine();
if(!f1.exists()){
f1.createNewFile();
}
else{
while(output.hasNext()){
String na=output.next();
if(na.equals(name)){
++i;
break;
}
}
if(i==0)
fw.write(name+" ");
else{
System.out.println("Please enter some different name");
}
}
fw.close();
input.close();
output.close();
}
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
can u help me with the coding of java, so i can copy a single file using command prompt.
so, i wanna run the java file from command prompt of windows, like "java "my java script" "my file target"" and make a copy of my "my file target" at the same directory without replace the old one.
please help me?
i came out with this
import java.io.*;
class ReadWrite {
public static void main(String args[]) throws IOException {
FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream("output.txt");
int n;
if(args.length != 1)
throw (new RuntimeException("Usage : java ReadWrite <filetoread> <filetowrite>"));
while((n=fis.read()) >= 0)
fos.write(n);
}
}
but the copy of the file is named as output.txt
can u guys help me with the coding, if i wanna choose my own output name?
if i type "java ReadWrite input.txt (this is the output name that i want)" on command prompt
really need help here...
import java.util.Scanner;
public class program_23{ // start of class
public static void main(String []args){ // start of main function.
Scanner input = new Scanner (System.in);
// decleration ang initialization of variables
String name = " ";
int age = 0;
int no_of_hour_work = 0;
double daily_rate = 0.0;
// get user input
System.out.print("Employee Name: ");
name = input.nextLine();
System.out.print("Employee Age: ");
age = input.nextInt();
System.out.print("No of hour(s) work: ");
no_of_hour_work = input.nextInt();
// compute for daily rate
daily_rate = no_of_hour_work * 95.75;
// display the daily rate
System.out.print("Dialy rate:"+ daily_rate);
}// end of main
}// end of class
pseudo-code:
input = open input stream for file1
output = open output stream for file 2
while (input.read() has more bytes):
write byte to output stream
close(input, output)