0

I have a String datatype called currency type declared and initialized as

private static String currencyType = null;

public static void main(String[] args) throws IOException {
    FileWriter fr = new FileWriter("test.txt", true);
    BufferedWriter bw = new BufferedWriter(fr);

    Scanner sc = new Scanner(System.in);
    currencyType = sc.next();
    bw.write(currencyType);
    bw.close();
}

I give value to this variable by a scanner , sometimes dinar , IQ , $ , Dollar , etc... I created a file just to write the currencyType to the file , the problem is that I just want to give that variable one similar value to all lines of the file , for example when I input $ , anytime I run the program when I want to write the currencyType value to the file it should write $ all of the time , the problem is it doesn't , why ? when I run the program again the currencyType will be null again , I want the variable to get the dataType once and not to be allowed to get back to null again , what is the problem here ?

Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
  • 1
    Could you read the current value in the file _before_ asking the user for currency type, and only ask if one hasn't been set already? – BeUndead Apr 07 '21 at 13:08
  • Store the configuration in some configuration file and update it only once from the user input. Next time just check if the config is already there and don't take input using scanner. It could be java properties file for example – muasif80 Apr 07 '21 at 13:10

1 Answers1

1

Every time you run the program, all variables will be initialized to their default value. If you want to save information between sessions, you will have to store it somewhere outside of your program, as is explained here: Best way to store data between program runs in java? I hope this answers your question.

Flipvs
  • 91
  • 4
  • Thanks man , this is what I want , but do you know how can I use it , there were so many answers ? – Coder Boy 9O9 Apr 07 '21 at 13:55
  • @CoderBoy9O9 https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html provides documentation on ObjectInputStreams and a short code snippet that you should be able to use for your problem. – Flipvs Apr 07 '21 at 14:52