Skip to content

Instantly share code, notes, and snippets.

@MaksymYakubets
Created September 21, 2021 22:57
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 MaksymYakubets/59e3abe08e6383663e714a99b8dd1921 to your computer and use it in GitHub Desktop.
Save MaksymYakubets/59e3abe08e6383663e714a99b8dd1921 to your computer and use it in GitHub Desktop.
demo_auto_140921
package ua.kiev.prog;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.time.Month;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
/*1. Напиши программу, которая выводит на экран надпись: JAVA HOME 10 раз.*/
System.out.println("TASK #1:");
for (int i = 0; i < 5; i++) {
System.out.println("JAVA HOME");
}
System.out.println("\n");
/*2.
В методе main создай объект Man, сохрани ссылку на него в переменную man.
Создай также объект Woman и сохрани ссылку на него в переменную woman.
Подсказка: для создания объекта Woman и занесения его ссылки в переменную woman используй конструкцию:
ТипПеременной имяПеременной = new ТипСоздаваемогоОбъекта();
В man.wife сохрани ссылку на ранее созданный объект Woman.
В woman.husband сохрани ссылку на ранее созданный объект Man (подсказка: woman.husband = man;).*/
System.out.println("TASK #2:");
Man man = new Man("Vasya", 38);
Woman woman = new Woman("Natalka", 42);
man.wife = woman;
woman.husband = man;
System.out.println(man.toString() + woman.toString());
/*3.
Написать функцию, которая возвращает минимум из двух чисел.*/
System.out.println("TASK #3:");
System.out.println(MinInt.min(12, 33));
System.out.println(MinInt.min(-20, 0));
System.out.println(MinInt.min(-10, -20));
System.out.println("\n");
/*4.
Добавь метод public static int convertToSeconds(int hour) который будет конвертировать часы в секунды.
Вызови его дважды в методе main с любыми параметрами.
Результаты выведи на экран, каждый раз с новой строки. */
System.out.println("TASK #4:");
System.out.println(Convert.convertToSeconds(new Random().nextInt((12)+1)) + " seconds");
System.out.println(Convert.convertToSeconds(new Random().nextInt((12)+1)) + " seconds" + "\n");
/*5.
Таблица умножения
Выведи на экран таблицу умножения 10 на 10 в следующем виде:
1 2 3 4 ...
2 4 6 8 ...
3 6 9 12 ...
4 8 12 16 ...*/
System.out.println("TASK #5:");
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));
System.out.println("\n");
/*6.
Подсчитать суммарную стоимость яблок.
За суммарную стоимость яблок отвечает переменная public static int applesPrice. */
System.out.println("TASK #6:");
Apple apple = new Apple();
apple.addPrice(50);
Apple apple2 = new Apple();
apple2.addPrice(100);
Apple apple3 = new Apple();
apple3.addPrice(500);
System.out.println("Стоимость яблок: " + Apple.applesPrice + " убитых енотов");
System.out.println("\n");
/*7.
Реализуте метод setName. */
System.out.println("TASK #7:");
Human human = new Human();
human.setName("Макс");
System.out.println(human.name);
System.out.println("\n");
/*8.
Времена года
Напишите метод checkSeason. По номеру месяца, метод должен определить время года (зима, весна, лето, осень) и вывести на экран.*/
System.out.println("TASK #8:");
checkSeason(12);
checkSeason(4);
checkSeason(7);
checkSeason(10);
System.out.println("\n");
/*9.
Создать класс Human. У человека должно быть имя (name, String), возраст (age, int), вес (weight, int), сила (strength, int).
*/
System.out.println("TASK #9:");
Human2nd human2 = new Human2nd();
human2.createHuman("Sub Zero", 38, 90, 100500);
System.out.println(human2.toString());
/*10.
Геттеры и сеттеры для класса Dog
Создать class Dog. У собаки должна быть кличка String name и возраст int age.
Создайте геттеры и сеттеры для всех переменных класса Dog.
*/
System.out.println("TASK #10:");
Dog dog = new Dog();
dog.setName("Sobaka");
dog.setAge(99);
System.out.println(dog.getName() + " is " + dog.getAge() + " years old pet");
System.out.println("\n");
/*11.
Задача: Программа вводит два числа с клавиатуры и выводит их максимум в виде "The max is 25".
*/
System.out.println("TASK #11:");
int max11 = 100;
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 && a > max11) {
max11 = a;
} else if (b > a && b > max11) {
max11 = b;
} else {
max11=max11;
}
System.out.println(text + max11);
System.out.println("\n");
/*12.
Чётные и нечётные цифры
Ввести с клавиатуры положительное число. Определить, сколько в введенном числе четных цифр, а сколько нечетных.
Если число делится без остатка на 2 (т. е. остаток равен нулю), значит оно четное.
Увеличиваем на 1 счетчик четных цифр (статическая переменная even).
Иначе число нечетное, увеличиваем счетчик нечетных цифр (статическая переменная odd).
Вывести на экран сообщение: "Even: а Odd: b", где а - количество четных цифр, b - количество нечетных цифр.
*/
System.out.println("TASK #12:");
int even = 0;
int odd = 0;
BufferedReader reader1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, input positive number");
int number = Integer.parseInt(reader1.readLine());
if (number > 0) {
while (number != 0) {
if (number % 2 == 0) {
even += 1;
} else {
odd += 1;
}
number = number / 10;
}
} else {
System.out.println(number + " is not positive number");
}
System.out.println("Even: " + even + " Odd: " + odd);
System.out.println("\n");
/*13.
Найти максимальное число в массиве
*/
System.out.println("TASK #13:");
System.out.println("Please, input positive numbers");
int[] array = getArray();
int max = maxInt(array);
System.out.println("Max number is " + max);
System.out.println("\n");
}
// #2
public static class Man {
String name;
int age;
Woman wife;
public Man(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " wife's name " + wife.name +
", she's " + wife.age + "\n";
}
}
public static class Woman {
String name;
int age;
Man husband;
public Woman(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " husband's name " + husband.name +
", he's " + husband.age + "\n";
}
}
// #3
public static class MinInt {
public static int min(int a, int b) {
if (a <= b) {
return a;
}
return b;
}
}
// #4
public static class Convert {
public static int convertToSeconds(int hour) {
int seconds = hour * 60 * 60;
return seconds;
}
}
// #5
public static String multiplicationTable(int number) {
String result = "";
for (int i = 1; i <= 10; i++) {
result += i * number + " ";
}
return result;
}
// #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) { // method 2 in 1
if (month == 1 || month == 2 || month == 12) {
System.out.println(Month.of(month) + " is Winter month from 1st method");
} else if (month == 3 || month == 4 || month == 5) {
System.out.println(Month.of(month) + " is Spring month from 1st method");
} else if (month == 6 || month == 7 || month == 8) {
System.out.println(Month.of(month) + " is Summer month from 1st method");
} else if (month == 9 || month == 10 || month == 11) {
System.out.println(Month.of(month) + " is Autumn month from 1st method");
} else {
System.out.println("There is no month " + month + " in this limited world // from 1st method");
}
switch (month) {
case 12: case 1: case 2: System.out.println(Month.of(month) + " is Winter month from 2nd method");
break;
case 3: case 4: case 5: System.out.println(Month.of(month) + " is Spring month from 2nd method");
break;
case 6: case 7: case 8: System.out.println(Month.of(month) + " is Summer month from 2nd method");
break;
case 9: case 10: case 11: System.out.println(Month.of(month) + " is Autumn month from 2nd method");
break;
default:
System.out.println("There is no month " + month + " in this limited world // from 2nd method");
}
}
// #9
public static class Human2nd {
String name;
int age;
int weight;
int strength;
public void createHuman(String name, int age, int weight, int strength) {
this.name = name;
this.age = age;
this.weight = weight;
this.strength = strength;
}
@Override
public String toString() {
return "name = " + name + "," + "\n" +
"age = " + age + "," + "\n" +
"weight = " + weight + "," + "\n" +
"strength = " + strength + "\n";
}
}
// #10
public static class Dog {
String name;
int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
// #13
public static int[] getArray() throws IOException {
int[] array = new int[5];
Scanner in = new Scanner(System.in);
for (int i = 0; i < array.length; i++) {
array[i] = in.nextInt();
System.out.println(i);
}
return array;
}
public static int maxInt(int[] array) {
int maxInt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > maxInt) {
maxInt = array[i];
}
}
return maxInt;
}
}
@Truewaydm
Copy link

Просмотрел

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