I have been given this task:
Write a program that takes as input a number n and a text string filename and writes n lines to the file where each line is of the form: i: sqrt(i) sqrt(i) sqrt(i). The first column ranges from 1..n whilst the first square root is to one decimal place, the second is to two decimal places and the third is to three decimal places.
And I came up with this code with help from one of my college tutors but..
public static void writeFile(final String filePath, final int n) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
final String format = "%-10s %-10.1f %-10.2f %-10.3f %n";
for(int i=1;i<=n;i++){
final double root = Math.sqrt(i);
writer.write(String.format(format,i+":",root ,root,root));
}
}
}
.... how would I include the text file that's meant to be used? I thought I'd do something similar to filepath = file.txt. for example. But I'm not sure how to incorporate that in the code. I came up with formatting it to the decimal places like the task asks. Would I need to include it in the for loop or outside the loop? Thanks
Your calling method should be passing in the file name as a part of the filePath variable.
If the filePath in the parameter doesnt have a file name, then you can define the file name inside the method and concatenate with the input filePath. You can use the derived file path to create your file writer object.
String completeFilePath = filePath.concat("file.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(completeFilePath))) {
...
}
Also please flush/close the writer object once you are done with the operation.
When you call your method you will pass the filePath as an argument. You only need to set in once in your code
writeFile("textfile.txt",5);
Related
So i have a program that creates a new file but need it to have a default file name if the user was to not enter anything, and was wondering if anyone could help with it.
So far i have the program asking the user for the file name but not sure what to do to set the default to for say "output.txt".
Here is a snip-it of my code:
//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();
Test what the user has entered as a filename. If it is an empty string, use the default filename.
You may want to "trim" the string too. A filename with leading or trailing whitespace characters would be a bad idea.
You have to test if the string is empty, which can be done with String#isEmpty in conjuction with String#trim, from the documentation:
isEmpty
public boolean isEmpty()
Returns true if, and only if, length() is 0.
That means, once we trim to remove whitespace, we can test if length is 0. Thus, any inputs that consist of just spaces will not be used as filenames, and will default, else it will used the given. You can apply this like so:
File file = new File(filename.trim().isEmpty() ? "output.txt" : filename);
try {
file.createNewFile();
} catch(IOException ex) {
//file was not created successfully
}
This will create a new File object, which will have a filename based on if the user inputted anything (whitespace excluded). file.createNewFile() will just create the file if it does not exist.
It's sure you need some condition for achieve this.
Perhaps, you probably need simple method like this:
isNotNullOrEmpty(filename) ? filename : defaultFileName;
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
I am assigned to write to another document using data from an input file, and calculating the mean and standard deviation from that file. I have an issue where my code is compiling correctly (according to Dr.Java) but is not giving an output to the output file. I have the code attached that I think is the problem area. It may either be the loops used or reading the file before the loops. Could anyone tell me if those places are the places of error?
// Create a File object passing it the filename
File readFile = new File(filename);
// Create a Scanner object passing File object
Scanner inputFile = new Scanner(filename);
// Perform a priming read to read the first line of the file;
line = inputFile.nextLine();
while (inputFile.hasNext()) //create a loop that continues until you are at the end of the file
{
while( Double.parseDouble(line) != -1)
{
sum += Double.parseDouble(line); //convert the line into a double value and add the value to the sum
count++; //increment the counter
line = inputFile.nextLine(); //read a new line from the file
}
mean = sum/count;
}
inputFile.close();
The output file code:
// Create a FileWriter object using "OutputFileProcess.txt"
File file = new File("OutputFileProcess.txt");
FileWriter fw = new FileWriter(file);
// Create a PrintWriter object passing the FileWriter object
PrintWriter outputFile = new PrintWriter("OutputFileProcess.txt");
// Print the results to the output file
outputFile.println(mean);
outputFile.println(stdDev);
// Close the output file
outputFile.close();
The code needs two loops, one to continue until the ned, and one to exclude any negative numbers in the text file. I should also introduce myself. I am Joe.
This might not be the core of your problem, but one of your while loops is obsolete.
If the inner condition
Double.parseDouble(line) != -1
becomes false, the outer while loop will not change the value of line and the inner while loop will never be entered anymore.
So at the moment the whole algorithm stops at the first -1.
A better way to write this down would be
while (inputFile.hasNext())
{
final String line = inputFile.nextLine();
final double lineAsDouble = Double.parseDouble(line);
if (lineAsDouble != -1D) {
sum += lineAsDouble;
count++;
}
}
final double mean = (double) sum / (double) count;
You should also consider parsing and comparing the values as Integers (if they all are), since comparing doubles with == is always dangerous.
I'm trying to solve a problem with creating a custom object with multiple parameters, but the parameters have to first be found one by one using a Scanner.
So basically, given an input file, where each line will represent a new object with multiple attributes (a county with its name, its crime index, etc.), I am using a Scanner with a while loop to scan the input file line by line, and then within that loop I'm using another while loop and a new Scanner that then scans each word within the line. That way, I can separate all of the object-to-be's attributes and then create the object by passing all of those values into the constructor.
What I can't figure out is how to delay the creation of the object until I have every word in each line, since every line in the input file is to be made into an object, with every word in that line being used as a parameter for the object.
Does anyone know how this can be done effectively without having to store all the words into an array or something like that?
Here's the constructor from the object class that will take all of the words of a line, which are all in proper order, and create a new object for each line in the input file:
public CountyItem(String countyName, String countyState, double countyPercentageClintonVoters, double countyResidentMedianAge,
int countyResidentMeanSavings, int countyPerCapitaIncome, double countyPercentageBelowPovertyLevel,
double countyPercentageVeterans, double countyPercentageFemale, double countyPopulationDensity,
double countyPercentageLivingInNursingHomes, int countyCrimeIndexPerCapita){
itemCountyName = countyName;
itemCountyState = countyState;
itemCountyPercentageClintonVoters = countyPercentageClintonVoters;
itemCountyResidentMedianAge = countyResidentMedianAge;
itemCountyResidentMeanSavings = countyResidentMeanSavings;
itemCountyPerCapitaIncome = countyPerCapitaIncome;
itemCountyPercentageBelowPovertyLevel = countyPercentageBelowPovertyLevel;
itemCountyPercentageVeterans = countyPercentageVeterans;
itemCountyPercentageFemale = countyPercentageFemale;
itemCountyPopulationDensity = countyPopulationDensity;
itemCountyPercentageLivingInNursingHomes = countyPercentageLivingInNursingHomes;
itemCountyCrimeIndexPerCapita = countyCrimeIndexPerCapita;
}
And here's my program's main method (still unfinished of course) that shows what I'm talking about with my plan to use nested while loops and two separate scanners to first read every line in the input file and then every word in that line:
public static void main(String[] args) throws IOException{
//Scanner and FileWriter
Scanner inFile = new Scanner(new FileReader("data/test1.txt")); //change this to use different test .txt file
FileWriter outFile = new FileWriter("data/output.txt");
//loops through each line in inputl.txt until end is reached
while(inFile.hasNextLine()){
String line = inFile.nextLine();
Scanner lineScanner = new Scanner(line);
//loops through every word in a given line
while(lineScanner.hasNext()){
}
lineScanner.close();
}
inFile.close();
}
You can use the builder pattern to slowly build up your constructor's dependencies, or you could also just introduce another constructor that takes in a File, and you can move all the logic from your main method into that constructor.
I have my default constructor set to at the moment.
//Default constructor
public MyInfo(String args) {
Name = "";
DateOfBirth = "";
Location = "";
AvgTemp = 0;
}
Since I am not sure what your actual .txt file looks like im going to assume that each line has Name,DateOfBirth,Location,AvgTemp.
Using a buffered reader, read the lines within a while loop and assign each value in an array after splitting the line by commas for example. Make sure to change your current variables to arrays before doing this.
BufferedReader br = new BufferedReader(new FileReader("Filename.txt"));
while (somevariable!=null){
somevairable=br.readLine();
String[] parts = somevariable.split(",");
Names[x]=parts[1]
And I will leave the rest up to you. Hopefully this is a decent start and you can follow the instructions. I suggest reading up on different types of file and buffered readers and writers.
Ok another question about my program that I'm writing called "Flight." In my tester I am creating an object from the Flight class called myFlight. The object has several fields (flight name, miles traveled, etc) but what I'm doing is reading the data from a file called input.txt and trying to put it into the object that I created. There are five lines of information on the file that I'm reading. For some reason I can't quite get it right, if anyone could help me fix this problem I would greatly appreciate it.
Here is the Constructor that has all the fields from my Flight class:
public Flight(String name, int num, int miles, String origin, String destination)
{
Airlinename = name;
flightnumber = num;
numofmiles = miles;
Origincity = origin;
Destinationcity = destination;
}
And the part of my program where I created the object and try to read the data from the file. I had created a blank constructor in my class too because I wasn't sure if I was supposed to put anything in the object when I created it.
Flight myFlight = new Flight();
File myFile = new File("input.txt");
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
myFlight = inputFile.nextLine();
}
inputFile.close();
}
}
Just in case you use special characters, you need to modify your program so you can read them correctly.
Scanner inputFile = new Scanner(myFile, "UTF-8");
On the other hand, if the text file contains the following, possibly subsequent calls to nextInt() generate a runtime exception.
Gran EspaƱa
1
1001
New York
Los Angeles
If that were the case, the reading should be different.
myFlight = new Flight(inputFile.nextLine(),
Integer.parseInt(inputFile.nextLine()),
Integer.parseInt(inputFile.nextLine()),
inputFile.nextLine(),
inputFile.nextLine());
As with any program, when adding more conditions to improve the model, it needs more and more code.
Good luck.
try
myFlight = new Flight(inputFile.next(), inputFile.nextInt(),
inputFile.nextInt(), inputFile.next(), inputFile.next());
You can't directly assign a string line to an object, you need to parse the line into parts and assign values to variables one by one.
How is your input text organized? The Scanner's nextLine() method is returning a String object and definitely you cannot assign that to a type Flight. There are different methods to get the different values in the Scanner like nextInt(), nextFloat().
Basically you can try like this
Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();
etc.
This is just a sample, you need to check the format you have in the input.txt file.