L5: Input and Output in Java

Introduction to Input and Output

  • Java allows interaction with the user via input and output operations.
  • The Scanner class provides a simple way to read inputs from the terminal.

Using the Scanner Class

  • To use the Scanner class, it must be imported from the java.util package:

    import java.util.Scanner;
  • Instantiating a Scanner Object: Create a Scanner object to read input from the terminal:

    Scanner input = new Scanner(System.in);
    • System.in connects the program to the standard input stream (keyboard input).
  • Reading Input:

    • nextLine(): Reads an entire line of input, including spaces until the newline character is encountered. Useful for capturing strings with multiple words.

      String line = input.nextLine();
    • next(): Reads the next token (a word or chunk of data separated by whitespace) and stops before spaces.

      String word = input.next();
  • Error Handling with Scanner:

    • hasNext(): Checks if the input stream has more tokens to read. Returns true if there’s more input.

      if (input.hasNextInt()) {
          int number = input.nextInt();
      }
    • If an invalid input type is encountered (e.g., trying to read an integer from a non-numeric input), a runtime error occurs. Use hasNext() methods (like hasNextInt()) to prevent this.

  • Common Issues:

    • Mixing nextLine() with other next() methods can cause problems since nextLine() reads the newline character as part of the input. Use nextLine() immediately after other next() calls to clear the input buffer:

      int age = input.nextInt();
      input.nextLine();  // Clear the buffer
      String name = input.nextLine();

Java Packages

  • Packages: Collections of related classes grouped together for specific functionalities.
    • java.lang Package: Automatically imported; contains fundamental classes like StringSystemMath.

    • java.util Package: Must be imported manually; contains utility classes such as ScannerArrayList.

    • Importing a package:

      import java.util.Scanner;
    • Use import java.util.*; to import all classes within a package (not recommended unless necessary to avoid ambiguity).

Formatting Output

  • Java offers various ways to format output, including System.out.printf()String.format(), and formatting classes from java.text.

System.out.printf()

  • Used for formatted output with placeholders called format specifiers:

    System.out.printf("Hello, %s! You are %d years old.\n", "John", 25);
    • Format Specifiers:
      • %s - String
      • %d - Integer
      • %f - Floating-point (default to 6 decimal places)
      Format SpecifierConversion Applied
      %%Inserts a % sign
      %x %XInteger hexadecimal
      %t %TTime and Date
      %s %SString
      %nInserts a newline character
      %oOctal integer
      %fDecimal floating-point
      %e %EScientific notation
      %gCauses Formatter to use either %f or %e, whichever is shorter
      %h %HHash code of the argument
      %dDecimal integer
      %cCharacter
      %b %BBoolean
      %a %AFloating-point hexadecimal
    • General format:
    % [flags] [width] [.precision] [argsize] typechar
    • Modifiers: Control the output’s precision, width, alignment, etc.:
      • %.2f - Limits floating-point to 2 decimal places.
      • %10s - Reserves 10 spaces for a string, right-aligned by default. Use %-10s for left alignment.

String.format()

  • Similar to printf, but returns a formatted string instead of printing it:

    String formatted = String.format("Total: %.2f", 123.456);

Number Formatting

  • NumberFormat Class:
    • Used for currency and percentage formatting.

    • Must be imported from java.text:

      import java.text.NumberFormat;
    • Example:

      NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
      System.out.println(currencyFormat.format(12345.678));  // Outputs: $12,345.68
    • Supports different locales (e.g., Locale.FRANCE) to format numbers in different currency styles.

  • DecimalFormat Class:
    • Customizes numerical formatting based on a specified pattern.

    • Must be imported from java.text:

      import java.text.DecimalFormat;
    • Example:

      DecimalFormat formatter = new DecimalFormat("0.00");
      String formattedNumber = formatter.format(123.456);  // Outputs: "123.46"
    • Patterns:

      • 0 - Guarantees a digit in that position.
      • # - Optional digit.
      • % - Displays a percentage by multiplying the number by 100.

Short Coding Problems Involving Command Line Inputs

  1. Read a User’s Name and Age:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter your name: ");
            String name = input.nextLine();
    
            System.out.print("Enter your age: ");
            int age = input.nextInt();
    
            System.out.printf("Hello, %s! You are %d years old.\n", name, age);
        }
    }
  2. Format a Price with Currency:

    import java.text.NumberFormat;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter the price: ");
            double price = input.nextDouble();
    
            NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
            System.out.println("Formatted price: " + currencyFormat.format(price));
        }
    }

Things to take note of

Importing classes

https://itknowledgeexchange.techtarget.com/coffee-talk/files/2022/08/java-scanner-import-image.gif