Take Input from user in java lecture 4 #javatutorial # learn tech with smriti
Notes of java
Take input from user
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all types of objects, data types, characters, files, etc to fully execute the I/O operations. There are two ways by which we can take input from the user or from a file
1.BufferedReader Class
2.Scanner Class
1.BufferedReader:
It is a simple class that is used to read a sequence of characters. It has a simple function that reads a character another read which reads, an array of characters, and a readLine() function which reads a line.
InputStreamReader() is a function that converts the input stream of bytes into a stream of characters so that it can be read as BufferedReader expects a stream of characters.
BufferedReader can throw checked Exceptions
Syntax :
BufferedReader bfn = new BufferedReader( new InputStreamReader(System.in));
Importing class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
2.Scanner:
It is an advanced version of BufferedReader which was added in later versions of Java. The scanner can read formatted input. It has different functions for different types of data types.
The scanner is much easier to read as we don’t have to write throws as there is no exception thrown by it.
It was added in later versions of Java
It contains predefined functions to read an Integer, Character, and other data types as well.
Syntax:
Scanner scn = new Scanner(System.in);
Importing Scanner Class: To use the Scanner we need to import the Scanner class from the util package as
import java.util.Scanner;
Inbuilt Scanner functions are as follows:
Integer: nextInt()
Float: nextFloat()
String : next() and nextLine()
Hence, in the case of Integer and String in Scanner, we don’t require parsing as we did require in BufferedReader.
Differences Between BufferedReader and Scanner
BufferedReader is a very basic way to read the input generally used to read the stream of characters. It gives an edge over Scanner as it is faster than Scanner because Scanner does lots of post-processing for parsing the input; as seen in nextInt(), nextFloat()
BufferedReader is more flexible as we can specify the size of stream input to be read. (In general, it is there that BufferedReader reads larger input than Scanner)
These two factors come into play when we are reading larger input. In general, the Scanner Class serves the input.
BufferedReader is preferred as it is synchronized. While dealing with multiple threads it is preferred.
For decent input, and easy readability. The Scanner is preferred over BufferedReader.
Examples of class :--------------
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class lecture4part1 {
public static void main(String args[]) throws Exception
{
/* BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String");
String str=obj.readLine();
System.out.println(str);
int in = Integer.parseInt(obj.readLine());
System.out.println(in);
*/
Scanner sc=new Scanner(System.in);
System.out.println("Enter String ");
String str=sc.nextLine();
System.out.println("Enter number");
float in =sc.nextFloat();
System.out.println(str);
System.out.println(in);
}
}
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Take Input from user in java lecture 4 #javatutorial # learn tech with smriti», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.