Skip to content

Instantly share code, notes, and snippets.

@OleksandrSenyk
Created September 17, 2021 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OleksandrSenyk/8ebff471a5bc75366d43d0993a430f20 to your computer and use it in GitHub Desktop.
Save OleksandrSenyk/8ebff471a5bc75366d43d0993a430f20 to your computer and use it in GitHub Desktop.
Oleksandr Senyk
package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
/* Task #1
Напиши программу, которая выводит на экран надпись: JAVA HOME 10 раз.*/
for (int i = 1; i <= 10; i++) {
System.out.println("JAVA HOME");
}
/* Task #2
В методе main создай объект Man, сохрани ссылку на него в переменную man.
Создай также объект Woman и сохрани ссылку на него в переменную woman.
Подсказка: для создания объекта Woman и занесения его ссылки в переменную woman используй конструкцию:
ТипПеременной имяПеременной = new ТипСоздаваемогоОбъекта();
В man.wife сохрани ссылку на ранее созданный объект Woman.
В woman.husband сохрани ссылку на ранее созданный объект Man (подсказка: woman.husband = man;).*/
Man man = new Man();
Woman woman = new Woman();
man.wife = woman;
woman.husband = man;
/* Task #3
Написать функцию, которая возвращает минимум из двух чисел.*/
System.out.println(min(12, 33));
System.out.println(min(-20, 0));
System.out.println(min(-10, -20));
/* Task #4
Добавь метод public static int convertToSeconds(int hour) который будет конвертировать часы в секунды.
Вызови его дважды в методе main с любыми параметрами.
Результаты выведи на экран, каждый раз с новой строки. */
System.out.println(convertToSeconds(1));
System.out.println(convertToSeconds(2));
/* Task #5
Таблица умножения
Выведи на экран таблицу умножения 10 на 10 в следующем виде:
1 2 3 4 ...
2 4 6 8 ...
3 6 9 12 ...
4 8 12 16 ...*/
System.out.println(multiplicationTable(1));
System.out.println(multiplicationTable(2));
System.out.println(multiplicationTable(3));
System.out.println(multiplicationTable(4));
System.out.println(multiplicationTable(5));
System.out.println(multiplicationTable(6));
System.out.println(multiplicationTable(7));
System.out.println(multiplicationTable(8));
System.out.println(multiplicationTable(9));
System.out.println(multiplicationTable(10));
/* Task #6
Подсчитать суммарную стоимость яблок.
За суммарную стоимость яблок отвечает переменная public static int applesPrice. */
Apple apple = new Apple();
apple.addPrice(50);
Apple apple2 = new Apple();
apple2.addPrice(100);
System.out.println("Стоимость яблок " + Apple.applesPrice);
/* Task #7
Реализуте метод setName. */
Human human = new Human();
human.setName("Макс");
System.out.println(human.name);
/* Task #8
Времена года
Напишите метод checkSeason. По номеру месяца, метод должен определить время года (зима, весна, лето, осень) и вывести на экран.*/
checkSeason(12);
checkSeason(4);
checkSeason(7);
checkSeason(10);
/* Task #9
Создать класс Human. У человека должно быть имя (name, String), возраст (age, int), вес (weight, int), сила (strength, int).
*/
Human2 human2 = new Human2();
human2.setParameters("Alex", 20, 65, 40);
System.out.println("Name " + human2.name + " age " + human2.age + " weight " + human2.weight + " strength " + human2.strength);
/* Task 10
Геттеры и сеттеры для класса Dog
Создать class Dog. У собаки должна быть кличка String name и возраст int age.
Создайте геттеры и сеттеры для всех переменных класса Dog.
*/
// решение в классах ниже
/* Task 11
Задача: Программа вводит два числа с клавиатуры и выводит их максимум в виде "The max is 25".
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String text = "The max is ";
System.out.println("Enter first number");
int a = Integer.parseInt(reader.readLine());
System.out.println("Enter second number");
int b = Integer.parseInt(reader.readLine());
if (a > b) {
max = a;
} else {
max = b;
}
System.out.println(text + max);
/* Task 12
Чётные и нечётные цифры
Ввести с клавиатуры положительное число. Определить, сколько в введенном числе четных цифр, а сколько нечетных.
Если число делится без остатка на 2 (т. е. остаток равен нулю), значит оно четное.
Увеличиваем на 1 счетчик четных цифр (статическая переменная even).
Иначе число нечетное, увеличиваем счетчик нечетных цифр (статическая переменная odd).
Вывести на экран сообщение: "Even: а Odd: b", где а - количество четных цифр, b - количество нечетных цифр.
*/
BufferedReader reader1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter positive number");
int number = Integer.parseInt(reader1.readLine());
if (number <= 0) {
System.out.println("Wrong input");
} else {
while (number != 0) {
if (number % 2 == 0) {
even += 1;
} else {
odd += 1;
}
number = number / 10;
}
}
System.out.println("Even: " + even + " Odd: " + odd);
/* Task #13
Найти максимальное число в массиве
*/
int[] array = getArray();
int max = maxArray(array);
System.out.println("Max number in array is " + max);
}
// #2
public static class Man {
public Woman wife;
}
public static class Woman {
public Man husband;
}
// #3
public static int min(int a, int b) {
if (a > b) {
return b;
} else {
return a;
}
}
// #4
public static int convertToSeconds(int hour) {
int seconds = hour * 60 * 60;
return seconds;
}
// #5
public static String multiplicationTable(int number) {
String res = "";
for (int i = 1; i <= 10; i++) {
res += i * number + " ";
}
return res;
}
// #6
public static class Apple {
public static int applesPrice = 0;
public static void addPrice(int applesPrice) {
Apple.applesPrice += applesPrice;
}
}
// #7
public static class Human {
private String name = "человек";
public void setName(String name) {
this.name = name;
}
}
// #8
public static void checkSeason(int month) {
if (month == 1 || month == 2 || month == 12) {
System.out.println("зима");
} else if (month == 3 || month == 4 || month == 5) {
System.out.println("весна");
} else if (month == 6 || month == 7 || month == 8) {
System.out.println("лето");
} else if (month == 9 || month == 10 || month == 11) {
System.out.println("осень");
} else {
System.out.println("Несуществующий месяц");
}
switch (month) {
case 12:
case 1:
case 2:
System.out.println("зима");
break;
case 3:
case 4:
case 5:
System.out.println("весна");
break;
case 6:
case 7:
case 8:
System.out.println("лето");
break;
case 9:
case 10:
case 11:
System.out.println("осень");
break;
default:
System.out.println("Несуществующий месяц");
}
}
// #9
public static class Human2 {
String name;
int age;
int weight;
int strength;
public void setParameters(String name, int age, int weight, int strength) {
this.name = name;
this.age = age;
this.weight = weight;
this.strength = strength;
}
}
// #10
public static class Dog {
String name;
int age;
public void setDogName(String name) {
this.name = name;
}
public void setDogAge(int age) {
this.age = age;
}
public int getDogAge() {
return age;
}
public String getDogName() {
return name;
}
}
// #11
public static int max = 100;
// #12
public static int even;
public static int odd;
// #13
public static int[] getArray() throws IOException {
int[] array = new int[4];
BufferedReader reader2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter numbers for array");
for (int i = 0; i < array.length; i++) {
array[i] = Integer.parseInt(reader2.readLine());
}
return array;
}
public static int maxArray(int[] array) {
int maxArray = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > maxArray) {
maxArray = array[i];
}
}
return maxArray;
}
}
@Truewaydm
Copy link

Просмотрел

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment