Java: решения типовых практических задач

Сборник для подготовки: каждая программа читает данные из input.txt и записывает ответ в output.txt. Код рассчитан на простые экзаменационные задачи по строкам, одномерным массивам и матрицам.

30практических задач с готовым кодом

Практика по строкам, массивам и матрицам

Во всех задачах используется один и тот же каркас. Внутри меняется только логика подсчета.

Мини-шаблон

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        // Здесь пишется решение задачи
        out.close();
    }
}

1 Посчитать цифры в строке

Загрузить строку из input.txt. Записать в output.txt количество цифр. Пример: abc123d5 -> 4.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

2 Сравнить количество заглавных латинских букв A в двух строках

Загрузить из input.txt две строки текста. Записать YES, если количество заглавных латинских букв A в строках совпадает, иначе NO.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s1 = in.hasNextLine() ? in.nextLine() : "";
        String s2 = in.hasNextLine() ? in.nextLine() : "";
        int c1 = 0;
        int c2 = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == 'A') {
                c1++;
            }
        }
        for (int i = 0; i < s2.length(); i++) {
            if (s2.charAt(i) == 'A') {
                c2++;
            }
        }
        if (c1 == c2) {
            out.print("YES");
        } else {
            out.print("NO");
        }
        out.close();
    }
}

3 Посчитать элементы массива, кратные 3

Загрузить из input.txt число N и N элементов одномерного массива. Записать количество элементов, кратных 3.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int count = 0;
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if (x % 3 == 0) {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

4 Посчитать заглавные латинские буквы

Загрузить строку. Записать количество символов от A до Z.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

5 Посчитать строчные латинские буквы

Загрузить строку. Записать количество символов от a до z.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'a' && c <= 'z') {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

6 Посчитать латинские гласные

Загрузить строку. Записать количество латинских гласных a, e, i, o, u без учета регистра.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = Character.toLowerCase(s.charAt(i));
            if (c == 'a' || c == 'e' || c == 'i' ||
                c == 'o' || c == 'u') {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

7 Посчитать слова в строке

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

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        s = s.trim();
        if (s.length() == 0) {
            out.print(0);
        } else {
            String[] words = s.split("\s+");
            out.print(words.length);
        }
        out.close();
    }
}

8 Посчитать вхождения заданного символа

В input.txt первая строка — текст, вторая строка — символ. Записать, сколько раз символ встречается в тексте.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        String t = in.hasNextLine() ? in.nextLine() : "";
        char need = t.charAt(0);
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == need) {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

9 Проверить строку на палиндром

Загрузить строку. Записать YES, если она читается одинаково слева направо и справа налево, иначе NO.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        boolean ok = true;
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                ok = false;
                break;
            }
        }
        out.print(ok ? "YES" : "NO");
        out.close();
    }
}

10 Найти сумму цифр в строке

Загрузить строку. Записать сумму всех цифр, которые встречаются в строке. Пример: a12b3 -> 6.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                sum += c - '0';
            }
        }
        out.print(sum);
        out.close();
    }
}

11 Найти длину самого длинного слова

Загрузить строку. Записать длину самого длинного слова.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        s = s.trim();
        int maxLen = 0;
        if (s.length() > 0) {
            String[] words = s.split("\s+");
            for (int i = 0; i < words.length; i++) {
                if (words[i].length() > maxLen) {
                    maxLen = words[i].length();
                }
            }
        }
        out.print(maxLen);
        out.close();
    }
}

12 Вывести строку в обратном порядке

Загрузить строку. Записать эту строку наоборот.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        String s = in.hasNextLine() ? in.nextLine() : "";
        for (int i = s.length() - 1; i >= 0; i--) {
            out.print(s.charAt(i));
        }
        out.close();
    }
}

13 Посчитать положительные элементы массива

Загрузить N и N целых чисел. Записать количество положительных элементов.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int count = 0;
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if (x > 0) {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

14 Найти сумму отрицательных элементов массива

Загрузить N и N целых чисел. Записать сумму отрицательных элементов.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int sum = 0;
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if (x < 0) {
                sum += x;
            }
        }
        out.print(sum);
        out.close();
    }
}

15 Посчитать четные и нечетные элементы массива

Загрузить N и N целых чисел. Записать два числа: количество четных и количество нечетных.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int even = 0;
        int odd = 0;
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if (x % 2 == 0) {
                even++;
            } else {
                odd++;
            }
        }
        out.print(even + " " + odd);
        out.close();
    }
}

16 Найти максимум и его индекс

Загрузить N и N чисел. Записать максимальный элемент и его индекс, считая с 0.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int max = in.nextInt();
        int index = 0;
        for (int i = 1; i < n; i++) {
            int x = in.nextInt();
            if (x > max) {
                max = x;
                index = i;
            }
        }
        out.print(max + " " + index);
        out.close();
    }
}

17 Найти минимум и максимум массива

Загрузить N и N чисел. Записать минимальный и максимальный элементы.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int first = in.nextInt();
        int min = first;
        int max = first;
        for (int i = 1; i < n; i++) {
            int x = in.nextInt();
            if (x < min) {
                min = x;
            }
            if (x > max) {
                max = x;
            }
        }
        out.print(min + " " + max);
        out.close();
    }
}

18 Посчитать элементы больше среднего арифметического

Загрузить N и N чисел. Записать количество элементов, которые больше среднего арифметического массива.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
            sum += a[i];
        }
        double avg = (double) sum / n;
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (a[i] > avg) {
                count++;
            }
        }
        out.print(count);
        out.close();
    }
}

19 Проверить, отсортирован ли массив по возрастанию

Загрузить N и N чисел. Записать YES, если массив не убывает, иначе NO.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        boolean ok = true;
        for (int i = 1; i < n; i++) {
            if (a[i] < a[i - 1]) {
                ok = false;
                break;
            }
        }
        out.print(ok ? "YES" : "NO");
        out.close();
    }
}

20 Найти индекс первого нуля

Загрузить N и N чисел. Записать индекс первого элемента, равного 0. Если нуля нет, записать -1.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int answer = -1;
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if (x == 0 && answer == -1) {
                answer = i;
            }
        }
        out.print(answer);
        out.close();
    }
}

21 Заменить отрицательные элементы на 0

Загрузить N и N чисел. Записать массив, где все отрицательные элементы заменены на 0.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
            if (a[i] < 0) {
                a[i] = 0;
            }
        }
        for (int i = 0; i < n; i++) {
            if (i > 0) {
                out.print(" ");
            }
            out.print(a[i]);
        }
        out.close();
    }
}

22 Вывести массив в обратном порядке

Загрузить N и N чисел. Записать элементы массива в обратном порядке.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        for (int i = n - 1; i >= 0; i--) {
            if (i < n - 1) {
                out.print(" ");
            }
            out.print(a[i]);
        }
        out.close();
    }
}

23 Сортировка пузырьком

Загрузить N и N чисел. Отсортировать массив по возрастанию и записать его.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (i > 0) out.print(" ");
            out.print(a[i]);
        }
        out.close();
    }
}

24 Сортировка выбором

Загрузить N и N чисел. Отсортировать массив по возрастанию методом выбора.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j] < a[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = a[i];
            a[i] = a[minIndex];
            a[minIndex] = temp;
        }
        for (int i = 0; i < n; i++) {
            if (i > 0) out.print(" ");
            out.print(a[i]);
        }
        out.close();
    }
}

25 Линейный поиск элемента в массиве

Загрузить N, затем N чисел, затем число X. Записать индекс первого X или -1, если X не найден.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        int x = in.nextInt();
        int answer = -1;
        for (int i = 0; i < n; i++) {
            if (a[i] == x) {
                answer = i;
                break;
            }
        }
        out.print(answer);
        out.close();
    }
}

26 Бинарный поиск в отсортированном массиве

Загрузить N, отсортированный массив и число X. Записать индекс X или -1.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        int x = in.nextInt();
        int left = 0;
        int right = n - 1;
        int answer = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (a[mid] == x) {
                answer = mid;
                break;
            } else if (a[mid] < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        out.print(answer);
        out.close();
    }
}

27 Посчитать положительные элементы матрицы

Загрузить N, M и элементы матрицы N на M. Записать количество положительных элементов.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int m = in.nextInt();
        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int x = in.nextInt();
                if (x > 0) {
                    count++;
                }
            }
        }
        out.print(count);
        out.close();
    }
}

28 Сумма главной диагонали квадратной матрицы

Загрузить N и матрицу N на N. Записать сумму элементов главной диагонали.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int x = in.nextInt();
                if (i == j) {
                    sum += x;
                }
            }
        }
        out.print(sum);
        out.close();
    }
}

29 Максимум в каждой строке матрицы

Загрузить N, M и матрицу N на M. Записать максимальный элемент каждой строки.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int m = in.nextInt();
        for (int i = 0; i < n; i++) {
            int max = in.nextInt();
            for (int j = 1; j < m; j++) {
                int x = in.nextInt();
                if (x > max) {
                    max = x;
                }
            }
            if (i > 0) {
                out.print(" ");
            }
            out.print(max);
        }
        out.close();
    }
}

30 Транспонировать матрицу

Загрузить N, M и матрицу N на M. Записать транспонированную матрицу M на N.

import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");
        int n = in.nextInt();
        int m = in.nextInt();
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                a[i][j] = in.nextInt();
            }
        }
        for (int j = 0; j < m; j++) {
            for (int i = 0; i < n; i++) {
                if (i > 0) {
                    out.print(" ");
                }
                out.print(a[i][j]);
            }
            if (j < m - 1) {
                out.println();
            }
        }
        out.close();
    }
}

Быстрые замены условий

Что нужно посчитатьУсловие в if
цифрыc >= '0' && c <= '9'
заглавные латинские буквыc >= 'A' && c <= 'Z'
строчные латинские буквыc >= 'a' && c <= 'z'
буква Ac == 'A'
четные числаx % 2 == 0
нечетные числаx % 2 != 0
кратные 3x % 3 == 0
положительныеx > 0
отрицательныеx < 0
нулиx == 0