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
Related
i am trying to get two inputs from the scanner (multiple times if needed).
The code in Question is in the else section of the main function but i decided to share everything since something may collide, i don't know. the problem is that the first scanner(the timed one) works fine but the other two scanners (scanner1) require me to first press enter once then input the data and press enter again. Also if it has something to do with having two scanners then i would like for scanner1 not to be timed. Its not tragic but a flaw and i would like to fix it. Can somebody help me because i am running out of ideas.
Sorry if i made spelling mistakes or if my gramar sucks.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class TimedScanner implements Runnable
{
public static void main(String[] args) throws IOException {
TimedScanner scanner = new TimedScanner();
System.out.print("Enter the number of searchagents you want to add in 15 second: ");
String input = scanner.nextLine(15000);
if (input == null)
{
System.out.println("\nNothing was entered. Continuing...");
}
else
{
Scanner scanner1 = new Scanner(System.in);
int number = Integer.parseInt(input);
File myFile = new File("searchagent_list.txt");
if (!(myFile.exists())) {
myFile.createNewFile();
}
for (int i = 0; i < number; i++) {
System.out.println("Press Enter!\nEnter the name of searchagent #"+(i+1));
String name = scanner1.nextLine();
System.out.println("Press Enter!\nEnter the adress of searchagent #"+(i+1));
String adress = scanner1.nextLine();
FileWriter fWrite = new FileWriter(myFile, true);
BufferedWriter bWrite = new BufferedWriter(fWrite);
bWrite.write(name+"##"+adress+"##\n");
bWrite.close();
}
System.out.println("Done");
}
}
private Scanner scanner;
private StringBuilder buffer;
private boolean reading;
private Thread t;
public TimedScanner()
{
scanner = new Scanner(System.in);
buffer = new StringBuilder();
reading = false;
t = new Thread(this);
t.setDaemon(true);
t.start();
}
public String nextLine(long time)
{
reading = true;
String result = null;
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < time && result == null)
{
try
{
Thread.sleep(30);
}
catch (InterruptedException e)
{
}
synchronized (buffer)
{
if (buffer.length() > 0)
{
Scanner temp = new Scanner(buffer.toString());
result = temp.nextLine();
}
}
}
reading = false;
return result;
}
#Override
public void run()
{
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
synchronized (buffer)
{
if (reading)
{
buffer.append(line);
buffer.append("\n");
}
else
{
// flush the buffer
if (buffer.length() != 0)
{
buffer.delete(0, buffer.length());
}
}
}
}
}
}```
The return after reading will solve your issue:
#Override
public void run() {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
synchronized (buffer) {
if (reading) {
buffer.append(line);
buffer.append("\n");
return;
} else {
// flush the buffer
if (buffer.length() != 0) {
buffer.delete(0, buffer.length());
}
}
}
}
}
but there is no benefit to create more than one Scanner reference. It's simply reading input from System.in stream.
The current code that I have reads only the last line of the file. Can someone help me establish a way so that the code reads a file line by line?
import java.util.*;
import java.io.*;
public class Searcher extends File {
Scanner scn;
public Searcher(String filename) {
super(filename);
}
public void search(String input)
{
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
}
int count = 0, fromIndex = 0;
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
public static void main(String[] args) {
Searcher search = new Searcher("src/ihaveadream.txt");
search.search("we");
}
}
appreciate any help !
while (scn.hasNext()) {
data = scn.nextLine();
}
You are replacing the value every time so you end up with the last value as that's what it gets set to in the end. Perhaps you wanted to append?
while (scn.hasNext()) {
data = data + scn.nextLine();
}
Good luck.
Your problem:
while (scn.hasNext()) {
data = scn.nextLine(); // right here
}
each next line replaces previous line.
Depending on what you need you can either:
make all lines as one String
data = data + scn.nextLine();
// another syntax to do the same:
data += scn.nextLine();
or use List to keep each line as separate element:
List<String> dataList = new ArrayList<>();
while (scn.hasNext()) {
dataList.add(scn.nextLine());
}
As everyone has already suggested, you are replacing the the data in your data variable in the while loop, and since the loop runs till the end of the file is reached, only the last line is stored in the data variable, and any further processing on data would get you results only from the last line, so what you can do is what everybody else here suggested, or you can try this as an alternative solution (close the while loop after you check for index values):
public void search(String input)
{
int count = 0, fromIndex = 0; //moved outside so that we don't reset it to 0 with every iteration of the loop
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
//} instead of here
//int count = 0, fromIndex = 0; move these variables outside of the loop
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
} //close it here
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
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.
I'm writing an application that is supposed to act like a cafe clip card. In other words, for every n:th (10 in my case) coffee that a customer purchases, he/she is awarded a free beverage. So, I'm quite done with the loop and I've been working on writing and reading from a file since I need the program to remember where it last left off in order for the customer to be able to close the application once he/she has been in the store. However, I'm having a difficult time figuring out how to write and read from a file, the code I have doesn't seem to output any .txt file. I need the code to have a closing condition, and upon entering this condition, it should write the "count" to a .txt file, and shut down. Once the program is being run the next time it should read from this .txt file so it knows where the count is at.
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";
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)");
}
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("countStorage.txt"))));
bw.write(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(newInputStreamReader(newFileInputStream(new File("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;
}
}
I see a few problems here. In your readFromFile() method, put a space after the keyword new. I also suggest putting a an absolute path for now (for debugging):
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
In your saveToFile() method, the constructor is wrong. Also put the full path to the file here:
bw = new BufferedWriter(new FileWriter("C:\\Temp\\countStorage.txt"));
Finally, in your saveToFile() method, write the count as a String. Writing it as an int refers to the Unicode character:
bw.write(Integer.toString(count)); //updated per Hunter McMillen
And invoke it...
FelixNeww f = new FelixNeww();
f.saveToFile(44);
System.out.println(f.readFromFile());
You need to invoke readFromFile or saveToFile in the place needed in order to become executed.
I suggest that you call readFromFile on the beginning of the Main method, use its returning contents, and saveToFile in the loop whenever the desired state changes and it needs to be saved.
I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}