Input&output - Ehsangood1/Programmign-2 GitHub Wiki
Input Types
In the Example, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:
nextBoolean() | Reads a boolean value from the user |
---|---|
nextByte() | Reads a byte value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
nextInt() | Reads a int value from the user |
nextLine() | Reads a String value from the user |
nextLong() | Reads a long value from the user |
nextShort() | Reads a short value from the user |
In this Example, I use different methods to read data of various types.
output
Console Output For console output, Java uses the System.out stream. The System.out.print and System.out.println methods are the most common methods for printing output. Example
-
System.out.print It will print in line.
-
System.out.println It will go to the next line and print there.
-
System.out.printf Stands for "print format" and is used for formatted output.
For Example: System.out.printf("The year is %d and the value of Pi is approximately %.2f%n", year, pi); %n is like pushing Enter on the keyboard, going to another line. But it works at the end of the test or passage, not in the middle. \n this one works in the middle.
Analyzing this Example:
printf: Stands for "print format" and is used for formatted output.
"The year is %d and the value of Pi is approximately %.2f%n": The format string where %d is a placeholder for an integer, %f is a placeholder for a floating-point number, and %n is a platform-independent newline character. year and pi: The variables to be formatted and inserted into the placeholders. The %d and %.2f are format specifiers:
%d: Formats the integer (year) as a decimal. %.2f: Formats the floating-point number (pi) to 2 decimal places.
Format specifiers
Common Conversion Types
%d | Decimal integer (e.g., 42) |
---|---|
%f | Floating-point number (e.g., 3.14159) |
%s | String (e.g., "Hello") |
%c | Character (e.g., 'A') |
%x | Hexadecimal integer (e.g., 0x2A for 42) |
%o | Octal integer (e.g., 052 for 42) |
File Input
To read from a file, you can use classes like FileReader and BufferedReader. The BufferedReader class provides buffering for efficient reading.
Example: Reading from a File Example
Explanation:
-
FileReader reads character files.
-
BufferedReader buffers the input for efficient reading.
-
The try-with-resources statement ensures that the file is closed automatically.
File Output
To write to a file, you can use classes like FileWriter and BufferedWriter.
Example: Writing to a File Example
Explanation:
- FileWriter writes to character files.
- BufferedWriter buffers the output for efficient writing.
- The try-with-resources statement is used to ensure the file is closed properly.