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.
Related
First I am sorry for all the questions but I am at a loss and have spent the last week working on this. I am new to the community so please work with me while I learn the format that I need to have in place.
Okay so I am working on my final project for a class and I have been given a help document and two .txt files. I have the .txt files on the right level where they can be called from any computer. I have also gotten my code to where it calls the right array to get a new submenu to come up after selection from the main menu. From there I am having problems calling a method (showdata) to have a JOptionPane pop up with an alert that must be displayed if there is a call for it from the .txt file namely it will have (*****) in front of it. I also have to add an option for the user to go back to the main menu instead of it just closing the program but I am unsure where I can put this option. I don't know if I should add it in the default loop or in my switch statement. Any help would be great. Thanks so much.
I have now included my .txt files below.
My main code is:
import java.util.Scanner;
public class Monitor {
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args) {
AnimalsHabitat methodCall = new AnimalsHabitat();
try {
int userChoice = mainMenu();
switch(userChoice) {
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
System.out.println("Press 0 to go back.");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
System.out.println("Press 0 to go back.");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3) {
loopError++;
if (loopError == 3) {
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e) {
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu() {
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
My help code is:
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat {
private String filePath;
final private Scanner scnr;
public AnimalsHabitat() {
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
if (textLine.contains("Details")) {
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" ")) {
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
} else {
System.out.print("Enter selection: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i) {
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
bailOut = true;
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2)) {
do {
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty()) {
bailOut = true;
}
if (textLine.contains(alertMessage)) {
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
} while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
This is my animals.txt
Details on lions
Details on tigers
Details on bears
Details on giraffes
Animal - Lion
Name: Leo
Age: 5
*****Health concerns: Cut on left front paw
Feeding schedule: Twice daily
Animal - Tiger
Name: Maj
Age: 15
Health concerns: None
Feeding schedule: 3x daily
Animal - Bear
Name: Baloo
Age: 1
Health concerns: None
*****Feeding schedule: None on record
Animal - Giraffe
Name: Spots
Age: 12
Health concerns: None
Feeding schedule: Grazing
This is my habitats.txt:
Details on penguin habitat
Details on bird house
Details on aquarium
Habitat - Penguin
Temperature: Freezing
*****Food source: Fish in water running low
Cleanliness: Passed
Habitat - Bird
Temperature: Moderate
Food source: Natural from environment
Cleanliness: Passed
Habitat - Aquarium
Temperature: Varies with output temperature
Food source: Added daily
*****Cleanliness: Needs cleaning from algae
Does this work for you?
Monitor.java
import java.util.Scanner;
public class Monitor
{
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args)
{
AnimalsHabitat methodCall = new AnimalsHabitat();
try
{
int userChoice = mainMenu();
switch(userChoice)
{
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3)
{
loopError++;
if (loopError == 3)
{
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e)
{
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu()
{
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
AnimalsHabitat.java
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat
{
private String filePath;
final private Scanner scnr;
public AnimalsHabitat()
{
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
if (textLine.contains("Details"))
{
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" "))
{
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
}
else
{
while(option != (i + 1))
{
System.out.print("Enter selection or enter " + (i + 1) + " to exit: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i)
{
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
}
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2))
{
do
{
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty())
{
bailOut = true;
}
if (textLine.contains(alertMessage))
{
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
}
while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData()
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Run example
javac AnimalsHabitat.java Monitor.java && java Monitor
Here is an example of some menu and submenu selection
package com.hnb;
public class Monitor {
public Monitor(FileParser fileParser) {
final Menu main = new Menu(fileParser.getOptions());
System.out.println("Welcome to the Zoo Monitoring System!");
MenuSelection selection = null;
Selection subselection = null;
do {
selection = main.displaySubMenu();
if(selection.isValid()){
do {
final Menu submenu = new Menu(selection.getSelection());
subselection = submenu.display();
if (subselection.isValid()) {
final Monitorable item = (Monitorable) subselection.getSelection();
System.out.println(item);
item.showAsterisk();
}
} while (!subselection.isExit());
}
} while (!selection.isExit());
}
public static void main(String[] args) {
new Monitor(new FileParser());
}
}
I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I am trying to learn Java. The other day I saw a website providing challenges to solve online. Here is the code project I choose: Fizz Buzz
This is where I am with the project:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
}
static Scanner scan;
static void openFile(File file) {
try {
scan = new Scanner((file));
} catch (FileNotFoundException e) {
System.out.println("Could not find file");
}
}
static int[] readLine() {
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int[] line;
line = new int[] { a, b, c };
return line;
}
static boolean nextLine() {
return scan.hasNextLine();
}
static String getLineOutput(int[] line) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= line[2]; i++)
if (i % line[0] == 0 && i % line[1] == 0) {
sb.append("FB ");
} else {
if (i % line[0] == 0) {
sb.append("F ");
}
if (i % line[1] == 0) {
sb.append("B ");
}
if (i % line[0] > 0 && i % line[1] > 0) {
sb.append(i + " ");
}
}
return sb.toString();
}
}
When I run the program in command prompt providing a path to a text file as the first argument my program seems to work fine. On CodeEval I get the following error:
CodeEval Error: Compilation was aborted after 10 seconds
Should I be accessing the file differently? Is there an exception I'm missing? None of my exceptions are prompting me.
In case this helps anyone in the future this code doesn't close the scanner. Unfortunately on CodeEval the code doesn't execute if this is the case.
Adding scan.close() at the end of main method (after while loop solved) the issue.
Edit: code difference
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
scan.close();
}
This question already has answers here:
Close Scanner without closing System.in
(3 answers)
Closed last month.
If I close one scanner object and make a new one and try to read some more input, I'm getting the NoSuchElementException exception.
My code works fine but it gives me a warning if I don't close the scanner. However, if I close it to get rid of the warning, I also close System.in... How do I avoid this?
Also, are there any consequences of not closing the scanner?
EDIT: Here's my code:
This is the NameAddressExists() method:
public void NameAddressExists() {
System.out.println("Enter name");
Scanner sc = new Scanner(System.in);
String n = sc.next();
System.out.println("Enter address");
String a = sc.next();
int flag = 0;
for(int i = 0; i < count; i++) {
if(array[i].name .equals(n) && array[i].address .equals(a)) {
System.out.println("True");
flag = 1;
}
}
if(flag != 1) {
new Agency(n, a);
}
sc.close();
}
This is the PanNumberExists() method:
public boolean PanNumberExists() {
Scanner s = new Scanner(System.in);
String n = "";
System.out.println("Enter the 5 digits");
try {
n = s.nextLine();
}catch(Exception e) {
System.out.println(e);
}finally {
s.close();
}
if(n .equals(this.PAN.subSequence(4,9))) {
return true;
}
else {
return false;
}
}
These methods are called from the following main() method:
public static void main(String args[]) {
Agency obj1 = new Agency("XYZ", "ABCD");
Agency obj2 = new Agency("XYZ", "ABCDEFG", "+91083226852521", "ab 1234567", "abcd12345ab");
// Agency obj3 = new Agency("XYZ", "TSRK", "36", "ab 1234567", "abcd12345ab");
obj1.NameAddressExists();
System.out.println(obj2.PanNumberExists());
}
As you can see, I first call the NameAddressExists() method, in which I open, use and close a Scanner named 'sc'. This works fine and gives me the correct output. Next, I call the PanNumberExists() method, in which I open another Scanner named 's' and try to use it to get some input from the user. This is where I receive the NoSuchElementException exception. If I leave the Scanner 'sc' open in my NameAddressExists() method, then I don't get this error.
You can use the Decorator pattern and create custom InputStream that can't be closed, then pass it to the Scanner
import java.io.IOException;
import java.io.InputStream;
public class PreventClosingInputStream extends InputStream {
private InputStream inputStream;
public PreventClosingInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
#Override
public int read() throws IOException {
return inputStream.read();
}
#Override
public void close() throws IOException {
// Don't call super.close();
}
}
Then, in your code:
PreventClosingInputStream in = new PreventClosingInputStream(System.in);
Scanner s = new Scanner(in);
// ...
s.close(); // This will never close System.in as there is underlying PreventClosingInputStream with empty close() method
Using try-with-resources:
try (PreventClosingInputStream in = new PreventClosingInputStream(System.in);
Scanner s = new Scanner(in);) {
// ...
// resources will be automatically closed except of System.in
}
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