how to reuse previous variable value after closing program - java

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

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.

You need to write the previous value in a persistent storage(like file).

Related

ArrayList<Integer> is not storing user-inputted integers in Java 8 (1.8)

*EDIT - SOLVED: After instantiating the Scanner Object, I used a delimiter as follows:
scanner.useDelimiter("");
Prior to this, I did try a delimiter that looked something like this (the exact code is available on Stack Overflow):
scanner.useDelimiter("\\p{javaWhitespace}");
...but it didn't work very well.
Thank you, everyone. If you're having this very same issue, try the first delimiter. If it doesn't work, upgrade your JDK to 13 then try it again.
Ok, my goal is to have a user input a credit card number which I would then like to store in an ArrayList of Integers and subsequently pass this list to my functions which will perform the Luhn algorithm in order to validate the provided number. Once the user presses Enter, the processing begins. This is a console application, nothing fancy.
Everything works beautifully...except the user-input part. None of the user-input is being stored into the declared ArrayList. I've inserted a print message to give me the size of the list just after the pertinent while-loop and....yep, 0. I also pass this list into a custom lengthChecker(ArrayList<Integer> list){} function subsequent to the relevant while-loop and it's printing my custom error-message.
I have declared local int variables within the scope of the while-loop and that wasn't helping much. I have tried getting the user's input as Strings and storing them in an ArrayList<String> list; then parsing the input but that didn't work very well (especially as I need the Enter key to behave as a delimiter such that the next steps can take place)
Anyways, here is the code to the function in question. Am I missing something obvious or should I just quit programming?
public void userInput() {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
System.out.println("Please input the card-number to be checked then press Enter: ");
while(scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
System.out.println("Length of list: " + list.size());
listLengthChecker(list);
scanner.close();
}
Thank you in advance.
I don't have the full context on all the code you've written to be able to solve your problem, but I can guess at what's going on. If you want to run any user I/O (such as the scanner), it must occur within the main method. I can only assume that you run your userInput() function within the main method in your class. However, because your userInput() function doesn't have the static keyword in its definition, it can't be accessed without initialising an object of the class - but as far as I can tell from your code, there is no object that the method could refer to. Add the static keyword (i.e. initialise the method as public static void userInput()) to be able to run the function as you intend.
As for the while loop - there's a small chance that this is a difference in Java versions (I use Java 11), but while(scanner.hasNextInt()) won't stop being true at the end of your line or when you press enter - only when you insert something (such as a character) that cannot be interpreted as an integer.
This while loop untill you enter any non integer value.
You finished entering all the integer values and then your program will print your list elements.

Feeding text file as standart input

I am trying to write program to called Triangle.java. The program should read 3 Integers from file as standard input and use them as parameters.
I did something like this:
Scanner input = new Scanner(System.in);
while(input.hasNextLine()) {
String TestName = input.nextLine();
int x = input.nextInt();
int y = input.nextInt();
int z = input.nextInt();
.......
}
and then I wanted to use x,y and z as parameters. I tried to compile the program on my ubuntu machine using command line javac Triangle.java<test.txt then run program using java Triangle.class.
Things do not seem to be working. Any suggestion would be highly appreciated.
Okay, a couple of problems with that code, but here's your main problem: You read more than you have
String TestName=input.nextLine();
int x =input.nextInt();
int y =input.nextInt();
int z =input.nextInt();
input.nextLine() will already read the ENTIRE line. So input.nextInt() will try to read ints from the next line yet again of which you don't even know if it exists.
That's not so much a problem with System.in because it will just prompt the user to enter some more ints (though I don't see how the TestName variable will be of any use anyway). But if you're using a file, this will become a problem.
Also, as a side note:
You can't really call input.hasNextLine() on a Scanner using System.in, because at that point in time, there will be no next line in the input stream. You first have to prompt the user to input some more before there will be a line, which means your while will never be executed.
However when you're using a file, obviously the check will work, so you should keep it around anyway.

How do I make a program with multiple classes run until the user specifies "E" instead of terminating at the end of Main?

I'm working on a program that allows a user to read a file, search for specific text (still in progress) in a file and write (append) to a file. The program has four classes, with one method in each, corresponding to each of the functions of the program.
My first class (containing Main) prompts the user to specify whether they want to read/search/write to a default file. Like so:
public class SimpleDBFunction {
public static void main(String args[]) throws IOException{
//Prompt user to provide input in accordance with desired function
System.out.println("Type 'R' to read a file; 'S' to search for text within a file; 'W' to write to a file; 'E' to exit");
//Initialize scanner and a string variable to hold the value of scanner variable
Scanner iChoice = new Scanner(System.in); //iChoice - inputChoice
String userChoice = iChoice.next();
//If user specifies "r" go to fileReader class
if(userChoice.equalsIgnoreCase("r")){
SimpleDBReader sdbrObject = new SimpleDBReader();
sdbrObject.sdbReader(args);
//If user specifies "s" go to textSearch class
}else if(userChoice.equalsIgnoreCase("s")){
SimpleDBSearch sdbsObject = new SimpleDBSearch();
sdbsObject.sdbSearch(args);
//If user specifies "w" go to fileWriter class
}else if(userChoice.equalsIgnoreCase("w")){
SimpleDBWriter sdbwObject = new SimpleDBWriter();
sdbwObject.sdbWriter(args);
//If user specifies "e" terminate program
}else if(userChoice.equalsIgnoreCase("e")){
System.exit(0);
}
iChoice.close(); //Close scanner, probably redundant here
}
}
The specific issue I have is that I want the program to run in this "state" of awaiting user input, even after the user has already prompted the program to perform one of the actions. I have tried to use both a while loop, and a do-while loop, to achieve this; but both ended up infinitely repeating whichever function the user specifies instead of running it once and returning to main. I also tried to utilize "break" in a few different positions (foolish of me), only to find that it terminates my program completely when it is reached.
I'm still a programming green-horn, so please bear with me. I know that my code isn't the most polished thing around and that there are a multitude of ways to improve it, but what I want is full functionality before I begin improving. If you wish to see the classes pertaining to reading, searching and writing please let me know.
Put Scanner iChoice = ... on top
Put everything between that and iChoice.close(); into an infinite loop
Only the scanner init and scanner close method will be outside this loop
String userChoice = ... needs to be inside the loop as well
A proper implementation would also wrap the loop in a try block and close the scanner in finally. Also the logic to perform inside the while loop based on user input might be a candidate for a separate method, to keep the try block easy to comprehend.

Not accepting user input eclipse java

I've been searching overflow questions and googling it for about half an hour and can't find an answer for this.
At first I thought it might be that I'm not closing my Scanner object. I added
inp.close();
after all my code,but still nothing.
I'm using Eclipse to create a simple Binary Search algorithm.
My problem is that it is not keeping my input. And what's even weirder is that it only accepts "5".
After pressing enter it only creates more spaces. It doesn't move on to the rest of the program.
I've also tried entering more values under the "skipped" ones without any success.
Here's some screenshots
nextInt() reads scans the next token of the input as an int.
If the input is not an int, then an InputMismatchException is thrown.
You can use next() to read the input, whatever its type is. And you can hasNextInt() to make sure the next input is an int:
Scanner inp = new Scanner(System.in);
if(inp.hasNext()) {
if(inp.hasNextInt()) {
int n = inp.nextInt();
// do something with n
} else {
String s = inp.next();
// do something with s
}
}
Actually, I have a theory - your Scanner code is working just fine, it's your binary search code that's broken. Whatever it's doing works on an input of 5 but falls into an infinite loop for other inputs.
Consider breaking up your input parsing code from your binary searching code (e.g. do input parsing in main() and define a binarySearch() function that main() calls) so that you can test them separately.

How to multiply numbers from a text file using JAVA [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to multiply numbers from a text file using JAVA but have no idea how.
4
12 4
16 8
14 1
12 8
The first number on the first line represents how many people there are within the document (line 2 "12 4" being the first person "12 8" being the last.)
4 (number of employees)
32 (hours employees have worked) 8 (wage per hour)
38 6
38 6
16 7
I'm trying to find how Java can skip line 1, read line two and multiply the two numbers and then do the same for the other lines.
Please can anyone explain how I could do this?
Cheers!
Here are all the things you need:
To read a file: Java: How to read a text file
To cast to integer: How to convert a String to an int in Java?
To multiply: use * operator
The assumption is that you have been given this as an assignment for homework and either you have not paid attention in class. The key to learning programming, is breaking the task down into manageable tasks.
In your case, write a program to read the input file and echo the output. Once you have that, you are part of the way there.
Next, put the numbers into integer variables. This will involve casting.
Then perform that math and spit out the output.
By performing small tasks, the problem becomes much easier.
I don't really understand your criteria unfortunately, but you seem to be able to understand the formula, and that's all you need. I recommend BufferedReader and FileReader to get the text from the file. From there, it's a good idea to start parsing your Strings around the spaces (there's a method for that), and you can then convert them to integers. Hopefully this puts you on the right track.
You definately need to read upon programming as a whole at first, because this should be one of the basic questions you should be able to answer.
I can give you a rough sketch on how to do it:
Construct a File object out of the place where the 'document' resides.
Read the input, definetely for novices, I would recommend using the Scanner class.
Read the first Integer or Line, save this number.
Read the following pair of Integers or Lines.
Multiply the read numbers.
Output the multiplication result.
You also might want to check some other concerns:
Should your program break on wrong input?
Should your program continue on wrong input?
You should take those things in consideration when reading either the Integers or the Lines out of the document.
I see you are having problems with BufferedReader. So to avoid the overhead of type conversion, you may consider using Scanner.
In your case,
Scanner scanner = new Scanner ("Path to your file with backslash characters escaped");
int myNumber = scanner.nextInt();
It will directly assign the number from the file to your variable.
Create a scanner to read the file
Skip the first line
Iterate over all the numbers
Multiply number pairs
Do something with those numbers
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// 1. Create a scanner to read the file
Scanner file = new Scanner(new File("textfile.txt"));
// 2. Skip the first line
file.nextLine();
// 3. Iterate over all the numbers
while(file.hasNextInt()) {
int hours = file.nextInt();
int wagePerHour = file.nextInt();
// 4. Multiply number pairs
int totalWage = hours * wagePerHour;
// 5. Do something with those numbers
<do something with the numbers>
}
}
}
This will skip the first line and print out the multiplied values for every following line. This is assuming that you are passing a file as a command-line argument.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Multiply{
public static void main(String[] args) throws FileNotFoundException{
File file = new File(args[0]);
Scanner sc = new Scanner(file);
// skip the first line
sc.nextLine();
int num_people;
int hours;
int total;
while(sc.hasNext()){
num_people = sc.nextInt();
hours = sc.nextInt();
total = num_people * hours;
System.out.println(total);
}
}
}

Categories