Br readline int java

Проверка вводимых данных BufferedReader

Начал изучать джаву. Добрался до ввода с консоли. Есть два способа, ну или я нашёл только два: сканер и буферридер. Со сканером вроде разобрался, там можно проверить вводимые данные с помощью методов hasNext. () Например, что введен инт можно так вот проверить:

Scanner sc = new Scanner(System.in); if (sc.hasNextInt()) int number = sc.nextInt(); else System.out.println("Не число."); 

Только там вместо sout надо «бросать исключения», но в этом я ещё не разобрался пока. А что делать с буферридером? Как его проверять? Читал что-то про «обрабатывать исключения» не совсем понял, как уже писал выше Может кто-то может на примере написать правильный код, например, для ввода интового значения. Я так понимаю, что проверить нужно на не пустоту и тип инт?

2 ответа 2

В Java есть 3 способа чтения входных данных из консоли:

  • использование Bufferedreader класса;
  • использование Scanner класса;
  • использование Console класса.

Разницу можно почитать здесь и здесь.

import java.io.BufferedReader; import java.io.Console; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class ConsoleInputExamples < public static void main(String[] args) < usingConsoleReader(); usingBufferedReader(); usingScanner(); >private static void usingConsoleReader() < Console console = null; String inputString = null; try < // cоздать объект console console = System.console(); // если console не равен null if (console != null) < // прочитать строку из пользовательского ввода inputString = console.readLine("Name: "); // вывод строки System.out.println("Name entered : " + inputString); >> catch (Exception ex) < ex.printStackTrace(); >> private static void usingBufferedReader() < System.out.println("Name: "); try< BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String inputString = bufferRead.readLine(); System.out.println("Name entered : " + inputString); >catch(IOException ex) < ex.printStackTrace(); >> private static void usingScanner() < System.out.println("Name: "); Scanner scanIn = new Scanner(System.in); String inputString = scanIn.nextLine(); scanIn.close(); System.out.println("Name entered : " + inputString); >> 

Одно из основных отличий между BufferedReader и классом Scanner заключается в том, что первый класс предназначен только для чтения строковых или текстовых данных, тогда как класс Scanner предназначен как для чтения, так и для анализа текстовых данных в примитивных типах Java, таких как int, short, float, double и long.

Читайте также:  Add text to document javascript

BufferedReader может только String читать, а Scanner может читать как String, так и другие типы данных, такие как int, float, long, double, float и т.д.

Таким образом, BufferedReader не предоставляет напрямую методов для чтения integer введённого пользователем. Можно использовать метод readLine(), однако изначально придется считывать integer в формате String.

В случае с методом parseInt(), он принимает String значение, парсит его как десятичный integer и возвращает.

Источник

BufferedReader in Java

In Java, BufferedReader class is the most enhanced way to read the character or text data from the file/keyboard/network. The main advantage of BufferedReader compared to FileReader class is:- In addition to the single character, we can also read one line of data. The BufferedReader class is defined in the java.io package and it is a subclass of the Reader class. It is available from Java 1.1 version onwards.

public class BufferedReader
extends Reader

Constructors of BufferedReader class

Since BufferedReader is a connection based, where one end is a Java application and another end is a file or keyboard. We must always pass that information to the constructor. Therefore, it doesn’t contain 0 parameter constructor.

It contains two constructors,

BufferedReader can’t communicate file or keyboard directly, it can communicate via some Reader object. We generally use FileReader class to communicate with the file, and InputStreamWriter class to communicate with the keyboard. FileWriter and FileReader class can directly communicate with the file. OuputStreamReader is a bridge from character streams to byte streams and InputStreamReader is a bridge from byte streams to character streams.

BufferedReader Methods

All these methods throws IOException when an input or output error occurs.

BufferedReader readLine() method

The readLine() method is the most important method of BufferedReader class. It reads a line of text. A line is considered to be terminated by any one of a line feed (‘\n’), a carriage return (‘\r’), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).

It returns a string containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached without reading any characters. It throws IOException when an input or output error occurs.

BufferedReader Object Creation Syntax

  • create a FileReader object by passing a valid file name.
  • create a BufferedReader object by using FileReader class object.

Syntax of BufferedReader to connect to file is,

// create BufferedReader and FileReader object FileReader fr = new FileReader("filename.txt"); BufferedReader br = new BufferedReader(fr);

Or, it can be written in single line as,

// In single line, BufferedReader br=new BufferedReader(new FileReader("filename.txt"));

To connect BufferedReader object with Keyboard,

  • pass System.in as argument to InputStreamReader object creation
  • pass InputStreamReader object as argument to BufferedReader object creation

Syntax of BufferedReader to connect to keyboard is,

// create BufferedReader and InputStreamReader object InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr);

Or, it can be written in single line as,

// In one line BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Java BufferedReader readline

We can use the BufferedReader class to read a complete line using the readLine() method. The file “data.txt” is available in the current directory. The character in the “data.txt” is,

10 20 30 40 50 60 70
Hello, World!
20.5 99.99

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderDemo < public static void main(String[] args) throws IOException < // create BufferedReader and FileReader object FileReader fr = new FileReader("data.txt"); BufferedReader br = new BufferedReader(fr); // read line from the file String line = br.readLine(); while (line != null) < // display System.out.println(line); line = br.readLine(); >// close stream br.close(); > >

Whenever we are closing BufferedReader then automatically internal FileReader also will be closed and we are not required to close them expliclitly.

The logic for the same program also can be written as,

// create BufferedReader object BufferedReader br = new BufferedReader(new FileReader("data.txt")); // read line from the file String line; while ((line = br.readLine()) != null) < // display System.out.println(line); >// close stream br.close();

Instead foe checking null we can also call the ready() method. The ready() method tells whether this stream is ready to be read.

// read line from the file and display while (br.ready())

Same program using above logic,

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderDemo < public static void main(String[] args) throws IOException < // create BufferedReader and FileReader object BufferedReader br = new BufferedReader( new FileReader("data.txt")); // read line from the file and display while (br.ready()) < System.out.println(br.readLine()); >// close stream br.close(); > >

InputStreamReader and BufferedReader in Java

If we want to read data from the keyboard at runtime while using BufferedReader then we must use InputStreamReader class. InputStreamReader is a bridge from byte streams to character streams. Keyboard given values are passed as binary form and InputStream converts them to String. Finally, BufferedReader can read them as String values.

How to take integer input from user in Java using bufferedreader? Below is the Java program to read data from keyboard using InputStreamReader and BufferedReader,

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class BufferedReaderDemo < public static void main(String[] args) throws IOException < // create BufferedReader object BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // read one line from the console System.out.print("Enter data: "); String str = br.readLine(); // display data System.out.println("Entered data is: "); System.out.println(str); // close stream br.close(); >>

Enter data: 10 20 30 40.5 22.9
Entered data is:
10 20 30 40.5 22.9

Enter data: Hello, World!
Entered data is:
Hello, World!

Program to Add Two Number

Java program to add two numbers by reading its values from the keyboard.

Procedure,
1) Create a BufferedReader object using InputStreamReader by passing System.in
2) Read the first number and store into a string
3) Read the second number and store into the string
4) Convert string to a number, if stored values can’t be converted to a number then it throws NumberFormatException, and program execution terminates
5) Add both values and display them.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class BufferedReaderDemo < public static void main(String[] args) throws IOException < // create BufferedReader object BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // read data from the console System.out.print("Enter first integer value: "); String firstNumber = br.readLine(); System.out.print("Enter second integer value: "); String secondNumber = br.readLine(); // convert string to integer int n1 = Integer.parseInt(firstNumber); int n2 = Integer.parseInt(secondNumber); // calculate sum value int sum = n1 + n2; // display result System.out.println("Sum= " + sum); // close stream br.close(); >>

Enter first integer value: 10
Enter second integer value: 20
Sum= 30

In the above program, we are directly converting the input value to int type value, if it is not a valid int type value then it will throw NumberFormatException. Example with input/output,

Enter first integer value: a
Enter second integer value: b
Exception in thread “main” java.lang.NumberFormatException: For input string: “a”

To solve this problem we can use Exception handling concept. We can use the try-catch block or try-with resources. Below program uses try-catch block.

import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class BufferedReaderDemo < public static void main(String[] args) < // create BufferedReader object BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); try < // read data from the console System.out.print("Enter first integer value: "); String firstNumber = br.readLine(); System.out.print("Enter second integer value: "); String secondNumber = br.readLine(); // convert string to integer int n1 = Integer.parseInt(firstNumber); int n2 = Integer.parseInt(secondNumber); // calculate sum value int sum = n1 + n2; // display result System.out.println("Sum= " + sum); >catch (NumberFormatException nfe) < System.out.println("Pass only integer numbers"); nfe.printStackTrace(); >catch (IOException ioe) < ioe.printStackTrace(); >finally < // close stream try < if(br != null) br.close(); >catch(IOException ioe) < ioe.printStackTrace(); >> > >

Enter first integer value: a
Enter second integer value: b
Pass only integer numbers
java.lang.NumberFormatException: For input string: “a”

Important points

Since all data are read as String, therefore converting from String to primitive type is the most important work while working with BuffereReader class. The different methods to convert string to primitives are given below. Assume “line” is a variable of String type.

Another important work is to convert lines into tokens. For this, we can use the split() method of the String class. Let us understand it through an example.

Problem description:- Read these values using readLine() of BufferedReader and store them to an int array.

We know that readLine() read one line at a time as a String.

// read line, String line = br.readLine();

Currently, line = “10 20 30 40 50″. Now, split this string based on the space(” “), using split() method of the String class.

// split into String array String str[] = line.split(" ");

Using Integer.parseInt() we can convert them to int type value. To store them in an array, first, create an int type array with a size of the str [] array.

// create int array with given size int arr[] = new int[str.length];

Currently,
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
arr[3] = 0;
arr[4] = 0;

// Convert str[i] to int and // assign them to array for (int i = 0; i

Finally,
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

Java Bufferedreader Example

Java program to find sum of array elements using BufferedReader ,

Program description:- Write a Java program to find the sum of array elements. The array size and elements will be given by the end-user, read those input values using BufferedReader class. In input, the first line gives the size of the array, and the second line contains array elements.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferedReaderDemo < public static void main(String[] args) throws IOException < // create BufferedReader object BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // read size of the array (first line) String line1 = br.readLine(); // convert String to int type int size = Integer.parseInt(line1); // create int array object with given size int arr[] = new int[size]; // read array elements (second line) String line2 = br.readLine(); // convert line2 to tokens String[] str = line2.split(" "); // update array for (int i = 0; i < size; i++) < // convert string str[i] to int // and assign to array element arr[i] arr[i] = Integer.parseInt(str[i]); >// calculate sum of array elements int sum = 0; for (int i = 0; i < size; i++) < sum = sum + arr[i]; >// display result (sum of array elements) System.out.println(sum); // close the stream br.close(); > >

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Br readline int java

Запись текста через буфер и BufferedWriter

Класс BufferedWriter записывает текст в поток, предварительно буферизируя записываемые символы, тем самым снижая количество обращений к физическому носителю для записи данных.

Класс BufferedWriter имеет следующие конструкторы:

BufferedWriter(Writer out) BufferedWriter(Writer out, int sz)

В качестве параметра он принимает поток вывода, в который надо осуществить запись. Второй параметр указывает на размер буфера.

Например, осуществим запись в файл:

import java.io.*; public class Program < public static void main(String[] args) < try(BufferedWriter bw = new BufferedWriter(new FileWriter("notes4.txt"))) < String text = "Hello World!\nHey! Teachers! Leave the kids alone."; bw.write(text); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

Чтение текста и BufferedReader

Класс BufferedReader считывает текст из символьного потока ввода, буферизируя прочитанные символы. Использование буфера призвано увеличить производительность чтения данных из потока.

Класс BufferedReader имеет следующие конструкторы:

BufferedReader(Reader in) BufferedReader(Reader in, int sz)

Второй конструктор, кроме потока ввода, из которого производится чтение, также определяет размер буфера, в который будут считываться символы.

Так как BufferedReader наследуется от класса Reader , то он может использовать все те методы для чтения из потока, которые определены в Reader. И также BufferedReader определяет свой собственный метод readLine() , который позволяет считывать из потока построчно.

Рассмотрим применение BufferedReader:

import java.io.*; public class Program < public static void main(String[] args) < try(BufferedReader br = new BufferedReader (new FileReader("notes4.txt"))) < // чтение посимвольно int c; while((c=br.read())!=-1)< System.out.print((char)c); >> catch(IOException ex) < System.out.println(ex.getMessage()); >> >

Также можно считать текст построчно:

try(BufferedReader br = new BufferedReader(new FileReader(«notes4.txt»))) < //чтение построчно String s; while((s=br.readLine())!=null)< System.out.println(s); >> catch(IOException ex)

Считывание с консоли в файл

Соединим оба класса BufferedReader и BufferedWriter для считывания с консоли в файл. Для этого определим следующий код программы:

import java.io.*; public class Program < public static void main(String[] args) < try(BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new FileWriter("notes5.txt"))) < // чтение построчно String text; while(!(text=br.readLine()).equals("ESC"))< bw.write(text + "\n"); bw.flush(); >> catch(IOException ex) < System.out.println(ex.getMessage()); >> >

Здесь объект BufferedReader устанавливается для чтения с консоли с помощью объекта new InputStreamReader(System.in) . В цикле while считывается введенный текст. И пока пользователь не введет строку «ESC», объект BufferedWriter будет записывать текст файл.

Источник

Оцените статью