Reputation: 469
public class UseVariableValueAgain{
public static void main(String args[]){
int x=6;
int y=7;
int LastValue=0;// for first time
LastValue=x+y+LastValue;
System.out.println("result"+LastValue);
Scanner scan = new Scanner(System.in);
int x1=scan.nextInt();
int y1=scan.nextInt();
int LastValue1=0;
LastValue1=x1+y1+LastValue1;//for first time
System.out.println("REsult using Scanner="+LastValue1);
}
}
Ressult=13
5
6
Result using Scanner=11
when i execute this program i got 13 output by default and by using scanner i enter 5,6 and output is 11 , Now I want to use (13,11)values for next time when i re-execute the program. but it give same result
Upvotes: 0
Views: 144
Reputation: 1424
You need to write the previous value in a persistent storage(like file
).
Upvotes: 0
Reputation: 5996
Your options in order of easiness:
1) Next time when you invoke the program, pass the values at the command line.
java UseVariableValueAgain 13 11
. You will have access to these values via args[]
array now. Keep in mind you will have to parse this to integer as args
is a String array.
2) Write these values to a file. (eg using BufferedWriter) and read it in the program using Scanner
or BufferedReader
;
3) Write the value to a database table. Read the values from the table in your program.
In all these options, you will have to check if this is a re-run by employing appropriate if-else conditions to check if the value needs to be read from user input or if it needs to be determined. If you are learning Java, I recommend trying all three options in that sequence.
Upvotes: 1