I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.
Related
Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.
For example (the txt file would contain the following numbers)
4567687509
569563
the marks are:
45%, 67%, 68%, 75%, 9%
56%, 95%, 63%
Write a method that will calculate the average of each set of marks as well as the overall average.
Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.
import java.io.*;
public class ReadFile {
public static int calcAvg (String x) throws IOException {
int avg = 0;
int count = 0;
FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
BufferedReader br = new BufferedReader (fr);
while ((x = br.readLine()) != null) {
if (count <= 2) {
}
}
br.close();
return avg;
}
considering an input file like
45676875
09569563
first I will have a method to read the file and transform it into a better structure to use.
public List<Integer> readFile() throws FileNotFoundException {
List<Integer> numbers = new ArrayList<>();
String line = "";
try {
FileReader fr = new FileReader("src/main/resources/numbers.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
for (int i = 0; i <= line.length() - 2; i+=2) {
char[] chars = line.toCharArray();
int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
numbers.add(number);
}
}
} catch (Exception e) {
System.out.println(e);
}
return numbers;
}
then I will have the method to calculate the AVG
public float calcAvg(List<Integer> numbers) throws IOException {
int sum = 0;
for (int number: numbers){
sum+= number;
}
return sum/(numbers.size());
}
of course, you need a start method to make things happen
something like
public void init() throws IOException {
List<Integer> numbers = readFile();
float result = calcAvg(numbers);
System.out.println(result);
}
It's as easy as that. You practically want people to do stuff for you, but this is a question and answer site. Here you'll see some code for getting the individual percentages. You'll figure the rest out.
File f = new File(path);
try {
Scanner scanner = new Scanner(f);
String line = scanner.nextLine();
for (int i = 0; i < line.length() - 1; i+=2) {
double percentage = Double.parseDouble(line.substring(i, i+2)) / 100.0;
}
} catch (Exception e) {e.printStackTrace();}
I have a text file with 5 lines, I wish to read in those lines and be able to number them 1 - 5, and save them in a different file. The numbers begin before the start of the line. I have tried to hard code in a loop to read in the number but I keep getting errors.
public class TemplateLab5Bronze {
static final String INPUT_FILE = "testLab5Bronze.txt";
static final String OUTPUT_FILE = "outputLab5Bronze.txt";
public static void main(String[] args) {
try {
FileReader in = new FileReader(INPUT_FILE);
PrintWriter out = new PrintWriter(OUTPUT_FILE);
System.out.println("Working");
BufferedReader inFile = new BufferedReader(in);
PrintWriter outFile = new PrintWriter(out);
outFile.print("Does this print?\n");
String trial = "Tatot";
outFile.println(trial);
System.out.format("%d. This is the top line\n", (int) 1.);
System.out.format("%d. \n", (int) 2.);
System.out.format("%d. The previous one is blank.\n", (int) 3.);
System.out.format("%d. Short one\n", (int) 4.);
System.out.format("%d. This is the last one.\n", (int) 5.);
/*if(int j = 1; j < 6; j++){
outFile.print( i + trial);
}*/
String line;
do {
line = inFile.readLine();
if (line != null) {
}
} while (line != null);
inFile.close();
in.close();
outFile.close();
} catch (IOException e) {
System.out.println("Doesnt Work");
}
System.out.print("Done stuff!");
}
}
This is all the code I have so far, excluding the import statements, the commented for loop is what I was trying to use. Is there another way to do this?
One way to do it is to add to the printWriter while looping through the existing file:
FileReader fr = new FileReader("//your//path//to//lines.txt");
BufferedReader br = new BufferedReader(fr);
try (PrintWriter writer = new PrintWriter("//your//other//path//newlines.txt", "UTF-8")) {
String line;
int num = 1;
while ((line = br.readLine()) != null) {
writer.println(num + ". " + line);
num++;
}
}
Note: I didn't put in any catch statements, but you might want to catch some/all of the following: FileNotFoundException, UnsupportedEncodingException, IOException
You don't need two PrintWriters. Use only one.
PrintWriter outFile = new PrintWriter(OUTPUT_FILE);
You can simply use a counter instead of a for loop (which you have incorrectly written as if - as mentioned by #Shirkam)
String line;
int count=1;
do {
line = inFile.readLine();
if (line != null) {
outFile.println( count++ +"." + line);
}
} while (line != null);
inFile.close();
This works fine at my end.
Okay, so I have to Write a program to create a file named Lab13.txt. Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
I've done this part already, but next I have to take those numbers in that file, create a new file, multiply all the numbers in the Lab13.txt file, and store them in the new file. My problem is when i create the new file, I'm only able to get it to multiply the last number printed from the Lab13.txt file. How do i get it to multiply all the numbers in Lab13.txt file by 10 and print them? This is probably a really simple solution and I feel so dumb for not being able to figure it out. Creating files is the new thing we're learning and my teacher is little to no help. :(
import java.io.*;
public class Lab13 {
public static void main(String ar[]) {
String toWrite = "";
int x=0;
try {
File file=new File("Lab13.txt");
FileWriter filewriter=new FileWriter(file);
BufferedWriter writer=new BufferedWriter(filewriter);
for(int i=0;i<10;i++) {
x=(int)(Math.random()*100);
writer.write(" "+x);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
File file1=new File("Lab13.txt");
FileReader filereader=new FileReader(file1);
BufferedReader reader=new BufferedReader(filereader);
String y;
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
You're never reading individual numbers from that line. And the x you multiplied with 10 was the last number you randomly generated in previous loop. That's why the problem.
Remove line -
toWrite += ("" + x*10);
Replace with -
String numArray = y.split(" ");
for (int i=0; i<numArray.length; i++) {
int newNum = Integer.parseInt(numArray[i]) * 10;
toWrite += ("" + newNum);
}
Your problem is here:
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
What reader.readLine() tells the reader to do is look for every newline character "\n" and process the chunks of text in between, and since you didnt add any, it treats the whole file as a single chunk.
What you can do instead is read the entire contents of the file into a string and then split it with the space delimiter (below is untested code):
String s = reader.readLine();
String[] allNumbers = s.split(" ");
for(String number : allNumbers) {
int currentNumber = Integer.parseInt(number);
bWriter.write(String.valueOf(currentNumber * 10) + " ");
}
public void multiply() throws Exception{
//reading from existing file
BufferedReader br = new BufferedReader(new FileReader("Lab13.txt"));
String l = br.readLine(); //assuming from your code that there is only one line
br.flush();
br.close();
String[] arr = l.split(" ");
//writing into new_file.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("new_file.txt"));
for(String a : arr){
bw.write((Integer.parseInt(a)*10) + " ");
}
bw.flush();
bw.close();
}
Just call this method. Should work. You basically need to split the String using space. once that done, parsing each String into Integer and multiplying. and again storing.
package com.test;
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
I am using a .txt file that contains: "Hello world\nHow are you doing this day?" I want to count whether a line contains a string or not, as well as the total number of lines. I use:
File file = new File(file_Path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
int j=0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("o")) { //<----------
i++;
}
}
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);
As I run and test line.contains("o"), it prints 2 lines containing "o", which is correct as well as 2 total lines. As I run line.contains("world"), it prints 0 lines which is wrong but gives 2 lines total. But what do I do wrong?
I tested it with a StringReader,
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
BufferedReader br = new BufferedReader(sr);
String line;
int i = 0;
int j = 0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("world")) { // <----------
i++;
}
}
System.out
.println("Lines containing the string: " + i
+ " of total lines " + j);
} catch (Exception e) {
e.printStackTrace();
}
Your file contents must not be what you think because I get
Lines containing the string: 1 of total lines 2
As the others answers and comments, I also think you may not be reading the file you think you are... (Relax it happens to everyone from time to time)
But, also it could be the encoder of the file or the version of the jdk you have, maybe if you could answer:
What did you use to create the file?
What OS you are running
this?
What JDK are you using?
It could clarify what may have happened
Just for you to know, I ran the same code you have using jdk8 and worked fine for me.
As follows the test I did:
1) I put your code in a function:
int countLines(String filename, String wording) {
File file = new File(filename);
String line;
int rowsWithWord = 0;
int totalRows = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
totalRows++;
if (line.contains(wording)) {
rowsWithWord++;
}
}
} catch (IOException e) {
System.out.println("Error Counting: " + e.getMessage());
}
System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
return rowsWithWord;
}
2) and ran the following unit test
#Test
public void testFile() {
try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write("Hello world\nHow are you doing this day?");
} catch (IOException e) {
System.out.println("Error writing... " + e);
}
int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
}
And I got the expected result:
Found 2 rows in 2 total rows
Found 1 rows in 2 total rows
I have been working on this code for the day and am almost at the finish line. What I want is that the code should work as a clip card, remembering the number of purchased coffees, and awarding the customer a free coffee every 10th purchase. I'm writing to a file and reading from it in order for a customer to be able to continue his clip card where he left of last time. So to my problem...I have properly been able to write my "count" variable to a file, and it is storing it correctly. However, every time I run the program again it starts off a 0 and I don't see why. I need it to save the current count, and read the count once run again. For example, if a customer has previously purchased 7 coffees and is returning to the store, his counter needs to start at 7. For some reason it is not doing that.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
FelixNeww f = new FelixNeww();
System.out.println(f.readFromFile());
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
f.saveToFile(count);
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Temp\\countStorage.txt"))));
bw.write(Integer.toString(count));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
You are currently setting your count variable to 0. You should set it to the value that's in the file. Do this just before the while loop:
count = f.readFromFile();
while(true) {
You should also implement a way to gracefully exit the while loop. For example, if the user enters "q", you can execute the break; statement to exit the while loop. And after your while loop, call key.close(); to close the Scanner object.
The scope of count variable is local in both instances
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
System.out.println(f.readFromFile());
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
In the readFromFile function, you read it from the file, return it, but don't keep track of it in a variable, why don't you replace the println with this inside your main:
count=f.readFromFile