User Input/Output
Output (Print to Console):
public class OutputExample {
public static void main(String[] args) {
System.out.println("Hello, World!"); // Print a line to the console
System.out.print("This "); // Print without a newline
System.out.print("is "); // Print without a newline
System.out.println("Java!"); // Print a line to the console
}
}
Input (Read from Console):
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a line of text
System.out.println("Hello, " + name + "!");
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer
System.out.println("You are " + age + " years old.");
// Remember to close the Scanner when done to avoid resource leaks
scanner.close();
}
}
Formatting Output:
public class FormatOutput {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
double salary = 50000.75;
// Format and print output
System.out.printf("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
}
}
Reading Input Using BufferedReader (Alternative):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a line of text: ");
String input = reader.readLine(); // Read a line of text
System.out.println("You entered: " + input);
// Remember to close the BufferedReader when done
reader.close();
}
}
Exception Handling:
Note that reading input using `Scanner` or `BufferedReader` can throw `InputMismatchException` or `IOException`, respectively. Proper exception handling should be implemented to handle potential errors.
These examples cover the basics of user input and output in Java. Depending on the complexity of your application, you might choose different methods for handling input and output.