JavaRush /Java Blog /Random EN /I/O streams and strings in Java
articles
Level 15

I/O streams and strings in Java

Published in the Random EN group
A class from the Java package library is used to enter data Scanner. I/O Streams and Strings in Java - 1This class must be imported in the program where it will be used. This is done before the public class begins in the program code. The class has methods for reading the next character of a given type from the standard input stream, as well as for checking the existence of such a character. To work with an input stream, you need to create an object of the Scanner class , specifying during creation which input stream it will be associated with. The standard input stream (keyboard) in Java is represented by an object - System.in. And the standard output stream (display) is an object already familiar to you System.out. There is also a standard stream for error output - System.err, but working with it is beyond the scope of our course.
import java.util.Scanner; // импортируем класс
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); // создаём an object класса Scanner
        int i = 2;
        System.out.print("Введите целое число: ");
        if(sc.hasNextInt()) { // возвращает истину если с потока ввода можно считать целое число
          i = sc.nextInt(); // считывает целое число с потока ввода и сохраняем в переменную
          System.out.println(i*2);
        } else {
          System.out.println("Вы ввели не целое число");
        }
    }
}
The method hasNextDouble()applied to an object of the class Scannerchecks whether a real number of type can be read from the input stream double, and the method nextDouble()reads it. If you try to read a value without first checking it, you may get an error during program execution (the debugger will not detect such an error in advance). For example, try entering a real number in the program below:
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double  i = sc.nextDouble(); // если ввести букву s, то случится ошибка во время исполнения
        System.out.println(i/3);
    }
}
There is also a method nextLine()that allows you to read an entire sequence of characters, i.e. string, which means the value obtained through this method must be stored in a class object String. In the following example, two such objects are created, then user input is written to them one by one, and then one string is displayed on the screen, obtained by combining the entered sequences of characters.
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1, s2;
        s1 = sc.nextLine();
        s2 = sc.nextLine();
        System.out.println(s1 + s2);
    }
}
There is also a method hasNext()that checks whether there are any characters left in the input stream. The class Stringhas a lot of useful methods that can be applied to strings (before the method name we will indicate the type of the value that it returns):
  1. int length()— returns the length of the string (the number of characters in it);
  2. boolean isEmpty()— checks if the string is empty;
  3. String replace(a, b)— returns a string where the character a (literal or variable of type char) is replaced by the character b;
  4. String toLowerCase()— returns a string where all characters in the original string are converted to lowercase;
  5. String toUpperCase()— returns a string where all characters in the original string are converted to uppercase;
  6. boolean equals(s)— returns true if the string to which the method is applied matches the string s specified in the method argument (you cannot compare using the ==string operator, like any other objects);
  7. int indexOf(ch)— returns the index of the character ch in a string (the index is the ordinal number of the character, but characters are numbered starting from zero). If the character is not found at all, it will return -1. If a character appears more than once in a string, it will return the index of its first occurrence.
  8. int lastIndexOf(ch)- similar to the previous method, but returns the index of the last occurrence if the symbol appears several times in the line.
  9. int indexOf(ch,n)— returns the index of the character ch in the string, but starts checking from index n (the index is the ordinal number of the character, but characters are numbered starting from zero).
  10. char charAt(n)— returns the code of the character located in the line under index n (the index is the serial number of the character, but characters are numbered starting from zero).
public class Main {
    public static void main(String[] args) {
        String s1 = "firefox";
        System.out.println(s1.toUpperCase()); // выведет «FIREFOX»
        String s2 = s1.replace('o', 'a');
        System.out.println(s2); // выведет «firefax»
        System.out.println(s2.charAt(1)); // выведет «i»
        int i;
        i = s1.length();
        System.out.println(i); // выведет 7
        i = s1.indexOf('f');
        System.out.println(i); // выведет 0
        i = s1.indexOf('r');
        System.out.println(i); // выведет 2
        i = s1.lastIndexOf('f');
        System.out.println(i); // выведет 4
        i = s1.indexOf('t');
        System.out.println(i); // выведет -1
        i = s1.indexOf('r',3);
        System.out.println(i); // выведет -1
    }
}
An example of a program that will display the indexes of all spaces in a line entered by the user from the keyboard:
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        for(int i=0; i < s.length(); i++) {
            if(s.charAt(i) == ' ') {
                System.out.println(i);
            }
        }
    }
}
Link to source: I/O streams and strings in Java
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION