13 August 2023

Input/Output In Java - learngreen.net

   

Input/Output In Java

The Scanner class is a subclass of the java.util package, allows to user to take input in Java programs. The Scanner class provides ways to scan different user inputs, including text, integers, doubles, and more. Here's a step-by-step tutorial for using the Scanner class to capture user input.

1. Import the Scanner Class

The Scanner class must first be imported, so add the following import statement to the top of your Java file


 import java.util.Scanner;

2. Create a Scanner Object

Create the object of  the Scanner class by using the new Keyword





 Scanner scanner = new Scanner(System.in);

 3. Reading Input from the User

The Scanner class has a number of methods that can be used to read various forms of input. Here are a few illustrations

To read a line of text (a string) from the user



 System.out.print("Enter your name: ");
 String name = scanner.nextLine( );

 4. For Reading an Integer




 System.out.print("Enter your age: ");
 int age = scanner.nextInt( );

 5. For Reading double/float from the user



 System.out.print("Enter a decimal number: ");
 double number = scanner.nextDouble( );

 6. For Reading boolean value from the user


 System.out.print("Are you tired? (true/false): ");
 boolean isTired = scanner.nextBoolean( );

 7. Reading Multiple Values in a Loop

While or for loops can be used to repeatedly read user input up until a predetermined condition is met. As an illustration, scanning a list of integers until the user types a certain number, such as 82.


 package Java;
 import java.util.Scanner;
 public class Number {
 public static void main(String[] args) {
 Scanner scanner = new Scanner(System.in);
 int number;
 System.out.println("Enter numbers (enter 82 to stop):");
	 while ((number = scanner.nextInt()) != 82) {
	     // Process the number
	 }
  scanner.close();
	}
  }

 8.Reading from Files

The Scanner class can be used to read data from files in addition to reading human input. When processing data from a text file, this is helpful.



 package Java;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;
 public class FileRDNGDemo {
 public static void main(String[] args) {
 try {
 /* Create a Scanner object to
  * read from the "document.txt" file	 
  */
 Scanner scanner = new Scanner(new File("document.txt"));
 /* Read each line from the file
  * as long as there's another line
  */
 while (scanner.hasNextLine()) {
 // Read the current line	 
 String line = scanner.nextLine();
 /* Process the line
  * (you can add your processing logic here) 
  * For example, you might print
  * it or analyze its content 
  * Printing the line as an example 
  */
         }
 /* Close the Scanner to release
  * resources associated with it
  */
 scanner.close();
  } catch (FileNotFoundException e) {
 // Handle the case where the file is not found	  
 System.out.println( e.getMessage());
 /* Output->
  * document.txt 
  * (The system cannot find the file specified)
  */
     }	 
    }
  }
  

9. Custom Delimiters

 The Scanner class reads input using whitespace as the delimiter by default. The delimiter can be altered to process input in various ways. Take a comma-separated list of values as an example.



 package Java;
 //Import the Scanner class
 import java.util.Scanner;
 public class Delimeter {
 public static void main(String[] args) {
 // Create a Scanner object with the given input string	 
 Scanner obj = new Scanner("London,Barcelona,Rome");
 // Set the delimiter to ","
 obj.useDelimiter(",");
 //Loop to process each token using the specified delimiter
 while (obj.hasNext()) {
 // Read the next token (city) based on the delimiter	 
 String Cities = obj.next();
 //Print the city name
 System.out.println(Cities);
	       }
 // Close the Scanner to release resources
 obj.close();
 /* Output->
  * London
  * Barcelona
  * Rome
  */
    }
  }

 10.  Using Regular Expressions

You may use regular expressions to match and extract particular patterns from input data using the  Scanner class.


 package Java;
 //Import the Scanner class
 import java.util.Scanner;
 public class RegularEXN {
 public static void main(String[] args) {
 // Create a Scanner object with the given input string	 
 Scanner scanner = new Scanner("Name: David, Age: 30");
/* Find the next occurrence of the
 * specified regular expression pattern
 */
 scanner.findInLine("Age: (\\d+)");
 /* Get the match result of
  * the regular expression
  */
 String ageMatch = scanner.match().group(1);
 /* Convert the matched string
  * (age) to an integer using parseInt
  */
 int age = Integer.parseInt(ageMatch);
 // Print the extracted age
 System.out.println("Age: " + age);
//Close the Scanner to release resources
 scanner.close();
 //Output-> Age: 30
     }
  }

Closing the Scanner

When you're done using the Scanner, it's a good idea to close it so that the resources it consumes can be released.


  scanner.close( );

 


 /* Example of how to take input from
  * the user using the Scanner class
  */
 package Java;
 import java.util.Scanner;
 public class InputDemo {
 public static void main(String[] args) {
 Scanner obj = new Scanner(System.in);
 System.out.print("Enter first number");
 int num1 = obj.nextInt();
 System.out.print("Enter second number");
 int num2  = obj.nextInt();
 int result = num1+num2;
 System.out.println("Addition of "+num1+" & "+num2+" is "+(result));
 obj.close();
	}
 }

 

Java uses the syntax "System.out.println" to display or print the argument sent to it. It writes the requested value to the standard output stream, sometimes known as "stdout."

The standard output stream refers to the location, such as the console or terminal, where a program's output is generally shown. The programmer can easily display messages, data, or results for debugging or informative purposes during program execution by using "System.out.println."

The class System

the variable out

a method called println( )

The Java "System" class is a part of the java.lang package. A static member named "out" in the System class denotes a java.io.PrintStream class object. 

The java.io.PrintStream class contains the "println" method, which is overloaded to enable printing of messages to the output destination, which is typically a console or file.

Java permits you to display output to the console using either System.out.println or System.out.print files. They are a part of the java.lang package and gives a means of interacting with the standard output stream, which is always the console. 

 

 Below is a detailed explanation of each. 

 

 System.from.print 

 The text has been printed to the console using this method without switching to a new line. Multiple outputs are printed to one line using this method.





 System.out.print("Hello, ");
 System.out.print("Friends!");
 

 


 //Output
 Hello, Friends!
 

 System.out.println

This method is used to print the text to the console and the "ln" word with print moves to the next line.

It is used to separate the outputs on the next line.


  System.out.println("Hello,");
  System.out.println("Friends!");
  

 


 //Output
 Hello,
 Friends!
 

This method is used to print an empty line as well by calling it without any arguments.



  System.out.println();
  //Prints an empty line
  

 Formatted Output:-

   Formatted output is a crucial component of programming that enables programmers to present information in a tidy and attractive way. The printf method in Java functions similarly to the printf function in C. You may format and regulate how various sorts of data are shown using this technique. This article will cover Java's formatted output as well as some practical printf method use examples.

Syntax of 'printf':-

The format string used by the printf method specifies placeholders for different data kinds. The data type to be formatted is indicated by a character after the placeholder %. The real values provided in the arguments then take the place of these placeholders


   System.out.printf("Format_string", arg1, arg2,...);
   

  Characters called formatting specifiers are included in the format string to specify how a specific argument should be formatted. Some frequently used formatting specifiers are listed below:-

  • %d: integer
  • %f: floating-point number
  • %s: string
  • %c: character
  • %b: boolean
  • %x: hexadecimal value


 //Formatting Integers
 int price = 1500;
 System.out.printf("The price of Shirt is Rs. %d.", price);
 

 


 // Output 
 The price of Shirt is Rs. 1500.
  

 


  //Formatting floating point number
  double price = 15.23;
  System.out.printf("The price is %.2f dollars.",price);
  

 


  // Output
  The price is 15.23 dollars.
  

 


  // Formatting Strings
   String name = "David";
   System.out.printf("Hello, %s!, name);
   

 


    // Output
     Hello, David!
   

 

No comments:

Post a Comment