Saving input means you:
Store the input that you obtained from a user/file/database/.. to a variable in Java
how it works?
- create a standard main-program setup
package SaveInput;
public class Basic {
void start () {
}
public static void main(String[] args) {
new Basic().start();
}
}
- let’s say we’ve got our data from an user input.
String inputByUser = "This input was given by a user";
- In this example we will read the data from the user with the Scanner.
- import the Scanner class
import java.util.Scanner;
- create a Scanner object, which contains the input
Scanner in = new Scanner(inputByUser);
- What kind of input do you except ? a line / a word / etc.. For all options go to this page.
I expect a line therefore, do I choose for the nextLine() method
String savedInput = in.nextLine();
Additional
If you want to see what data you saved, print the variable:
- import the PrintStream class
import java.io.PrintStream;
- Create a PrintStream object
PrintStream out = new PrintStream(System.out);
- use one of the print methods in the class PrintStream (e.g. println | printf | print)
void start () {
// rest of start method
out.println(savedInput);
}
program
package SaveInput;
import java.io.PrintStream;
import java.util.Scanner;
public class Basic {
String inputByUser = "This input was given by a user";
PrintStream out = new PrintStream(System.out);
void start () {
Scanner in = new Scanner(inputByUser);
String savedInput = in.nextLine();
out.println(savedInput);
}
public static void main(String[] args) {
new Basic().start();
}
}
output
This input was given by a user
synonym
- save variable
- save InputStream
- save String
- save Scanner Object
- read Input