Смотритель: hubert
  • ,

IDEA 2016 3.4 как изменить внешний вид подсказок?

Здравствуйте. В новой идее переменные в конструкторах ( и не только ) стали выделяться самой программой ( видно на скриншоте ) Скажите пожалуйста — есть ли какая-нибудь возможность управлять внешним видом этих подсказок? (хотелось бы сделать их текст ярче)
Спасибо.

P.S. создать топик в разделе IDEA почему-то не смог, извините.
  • ,

Использование UML в разработке и сопровождении java-программ

UML (Unified Modeling Language) — унифицированный язык моделирования.
Узнал об UML из замечательного повествования на форуме от alex8894
Обзор CASE-средств для построения диаграмм UML.
В книге «UML for Java Programmers» Robert Cecil Martin, насколько понял, используются стандарты UML 1, т. к. ныне действующий UML вступил в действие уже после её опубликования. Однако, полагаю, основные принципы построения подобных блок-схем остались без существенных изменений.
Учебный пример из лекции:

/*
 * © Volodya Mozhenkov 2015
 * GPL version 3.0
 * Almost University http://www.almost-university.com/
 * VladimirMozhenkov@yahoo.com
 *
 */
// файл Main.java
public class Main
{
    private static void printRes(MyResult r)
    {
        if(r.hasResult())
        {
            System.out.print("Результат исполнения: ");
            System.out.println(r.getResult());
        }
        else
        {
            System.out.println("Результат отсутствует");
        }
    }
    public static void main(String[] args)
    {
        MyCalculator c1 = new MyCalculator('/');
        MyResult r = c1.calculate(4, 2);
        printRes®;
        r = c1.calculate(40, 13);
        printRes®;
        r = c1.calculate(1, 0);
        printRes®;

        c1 = new MyCalculator('^');
        r = c1.calculate(2, 25);
        printRes®;
    }
}

// файл MyCalculator.java
public class MyCalculator
{
    private class ResultClass implements MyResult
    {
        boolean valid;
        int result = 0;
        public ResultClass()
        {
            valid = false;
        }
        public ResultClass(int result)
        {
            this.result = result;
            valid = true;
        }
        public int getResult()
        {
            return result;
        }
        public boolean hasResult()
        {
            return valid;
        }
    }
    private char operation;

    public MyCalculator(char operation)
    {
        this.operation = operation;
    }

    public MyResult calculate(int a, int b)
    {
        MyResult res;

        switch(operation)
        {
            case '*':
                res = new ResultClass(a*b);
                break;
            case '/':
                if(b!=0)
                {
                    res = new ResultClass(a/b);
                }
                else
                {
                    res = new ResultClass();
                }
                break;
            case '+':
                res = new ResultClass(a+b);
                break;
            case '-':
                res = new ResultClass(a-b);
                break;
            default:
                res = new ResultClass();
                break;
        }
        return res;
    }
}

// файл MyResult.java
public interface MyResult
{
    public int getResult();
    public boolean hasResult();
}

И, используя одну из бесплатных версий программ, довольно быстро нарисовал такую блок-схему этой программы на смартфоне (естественно с шибками, так как только начал интересоваться UML):
Image Hosted by PiXS.ru
Интересно было бы посмотреть и сравнить с тем, какую UML- схему/диагамму этой же программы построит Intellij IDEA.
  • ,

IntelliJ IDEA со смартфона/планшета?! - Можно,оказывается, и так!

Неплоха AIDE для работы в Android (http://www.android-ide.com/), но к возможностям и удобствам IntelliJ IDEA быстро привыкаешь. И когда больше времени проводишь не у стационарного персонального компьютера, а со смартфоном, то невольно начинаешь мечтать о полноценном удаленном доступе к PC. Первые мои опыты с программой TeamViewer показали, что это вполне достижимо. Однако невысокое быстродействие (даже в локальной сети всё гонится через Интернет, а не напрямую по wi-fi через роутер) не очень пришлось по вкусу.
Понравилась же программа Microsoft Remote Desktop: www.microsoft.com/en-us/download/details.aspx?id=50042 — эта программа ставится на PC, а на мобильное устройство под управлением Андроида — с play.google.com. В ней по wi-fi идёт прямой доступ через роутер (HD видео изображение с РС хоть и отрывисто, но звук неплох — и это на дешевом смартфоне c Android 5.0 !).
Что ж, теперь взаимодействие с любой IDE вполне осуществимо и удаленно, особенно когда для удобства используешь со смартфоном(планшетом) беспроводную клавиатуру. Очень этому рад!
  • ,

Сложно ли пересесть с Java на C++ или C#?

Добрый день. Скажите пожалуйста — на сколько сложно будет пересесть с Java на C++ или C# после окончания курса Javarush? Недавно узнал, что моя профильная специальность будет требовать именно знание языков майкрософт, но заканчивать курс заранее совсем не хочется, так как я чувствую, что знания из него откладываются в голове куда лучше разных книг.
  • ,

Вложенные, локальные и анонимные классы

Всем доброго времени суток! Стал глубже копать разновидности классов и написал код, который содержит класс. Этот класс содержит метод main() и статический вложенный класс. Статический вложенный класс содержит метод. Метод создает локальный класс. Локальный класс имеет метод, который создает анонимный класс обрамляющего класса (сильно сомневаюсь, что подобные извращения имеют место в практике программирования, но чисто спортивного интереса ради решил помудрить, так что просьба — не бросаться камнями. Раньше времени, во всяком случае). Упрощенно это выглядит так:


class Outer { // ОБРАМЛЯЮЩИЙ КЛАСС
    static class Inner { // СТАТИЧЕСКИЙ ВЛОЖЕННЫЙ КЛАСС
        int doInnerThings() { // ЛОКАЛЬНЫЙ МЕТОД ВНУТРЕННЕГО КЛАССА
            class LocalInner { // ВНУТРЕННИЙ ЛОКАЛЬНЫЙ КЛАСС
                int doLocalInnerThings() { // МЕТОД ЛОКАЛЬНОГО КЛАССА
                    new Outer(5) {}; // ВНУТРЕННИЙ ЛОКАЛЬНЫЙ АНОНИМНЫЙ КЛАСС
                }
            }
        }
    }
}


Цель: создать переменную в анонимном классе, используя обрамляющий супер-класс, и «перебросить» аргумент этой переменной вплоть до внутреннего класса, присвоив его переменной внутреннего класса, соответственно.

Ниже приведен чуть расширенный код, с моими набросками.


class Outer { // ОБРАМЛЯЮЩИЙ КЛАСС
    int outerValue = 0;

    Outer(int a)
    {
        this.outerValue = a*a;
    }

    int getValue() {
        return outerValue;
    }

    static class Inner { // ВНУТРЕННИЙ СТАТИЧЕСКИЙ КЛАСС
        public  int innerValue = doInnerThings();

        int doInnerThings() {
            final int innerValue = 0; // КАК ПЕРЕДАТЬ ЗНАЧЕНИЕ ЭТОЙ ПЕРЕМЕННОЙ ИЗ КЛАССА НИЖЕ?

            class LocalInner { // ЛОКАЛЬНЫЙ КЛАСС
                final public int localInnerValue;

                LocalInner() {
                    localInnerValue = doLocalInnerThings();
                }

                int doLocalInnerThings() {
                    final int[] localInnerAnonValue = {0};

                    new Outer(5) { // АНОНИМНЫЙ КЛАСС
                        @Override
                        int getValue()
                        {
                            localInnerAnonValue[0] = super.getValue();
                            return localInnerAnonValue[0];
                        }
                    };
                    
                    return localInnerAnonValue[0];
                }

                int getlocalInnerValue() {
                    return this.localInnerValue;
                }
            }

            return innerValue;
        }
    }

    public static void main(String[] args) {
        Outer.Inner test = new Outer.Inner();
        System.out.println(test.innerValue);
    }
}


Проблема: метод
int doInnerThings()
Не могу присвоить переменной этого метода "innerValue" значение переменной "localInnerValue" из локального класса "LocalInner"

Буду рад помощи! :)
  • ,

Прерывания работы нити (interrupte thread).

Набросал два класса, наследующихся от Runnable. В них простая начинка ( Thread.sleep и sout). Я изучал вопрос прерывания работы нитей при помощи interrupted и isInterrupted. Почему-то прерывания не происходит, а выполнение программы зациклавается и вылетает ошибка:
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Producer.run(Producer.java:15)
	at java.lang.Thread.run(Thread.java:745)
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.javarush.test.myExample.example.thread.Consumer.run(Consumer.java:15)
	at java.lang.Thread.run(Thread.java:745)

После вылета ошибки работа нитей продолжается бесконечно. Но если убрать из классов, унаследовавшихся от Runnable, вызов Thread.sleep, то программа отрабатывает нормально. В чем загвоздка, почему вылетает ошибка и почему не завершается работа программы???
Вот main:
public class Solution
{
    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(new Producer());
        Thread thread2 = new Thread(new Consumer());

        thread1.start();
        thread2.start();

        Thread.sleep(1500);

        thread1.interrupt();
        thread2.interrupt();
    }
}


Первый класс:
public class Producer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Producer");
        }
    }
}


Второй класс:
public class Consumer implements Runnable
{
    @Override
    public void run()
    {
        while (!Thread.interrupted())
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println("Consumer");
        }
    }
}

Спасибо за комментарии к теме)
  • ,

Учим английский (навыки чтения). Уровень 1.

Все мы учили English, как говорится, хоть где-нибудь и хоть как-нибудь.
Сам я в школе и институте прошляпил английский (хотя получил по нему отлично, так как помог в каникулы с ремонтом класса в школе — красил, шпаклевал и т.п., а в институте в лихие 90-е некоторым преподам было банально не до нас).

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

В конце данного топика я приведу классический текст адаптированной сказки «Кот в сапогах» Шарля Перро (куда же мы денемся без котиков). Вы должны его с листа читать как русский текст, так как:
  • словарный запас мал, соответствует уровню Starter/Elementary (Total words: 2665 Unique words: 560)
  • содержание текста, надеюсь, всем знакомо :)

Вероятно, пару-тройку незнакомых слов, могут встретить и люди со средним знанием english-а, так, что и им, возможно, будет полезно прочитать эпическую фентези про котэ-победителя гигантов.
Кому тяжело — учите встретившие слова и разбирайте грамматику.
Слова лучше заносить в онлайн-тренинги английского (я, например, предпочитаю, lingualeo.ru, который имеет plugin позволяющий заносить прямо из браузера, тыкнув на незнакомое слово) и тренировать там периодически. Аналогично многие сайты предлагают и тренинг грамматики.

Если интересно, могут периодически выкладывать и другие тексты (со временем и технические, возможно адаптированные). Чтобы JR-шовцы могли периодически тренировать навык перевода. Напишите в комментариях, стоит ли.

P.S. К администрации, текст сказки взят отсюда: english-e-books.net (graded readers ebooks – best choice to learn English. Download or read online for free! ), так что, думаю проблем с нарушением юрид прав нет.

Собственно текст.
Charles Perrault. Puss in boots.
CHAPTER ONE
Once upon a time there was a poor miller. He lived in a small house, together with his three sons. The miller worked at the mill, and his sons helped him. The miller had no horse. He used his donkey to bring wheat from the fields.
The years went by. The miller grew old and died. His sons decided to divide their father's things among themselves. That was easy: he had almost nothing to leave to his sons. Only his mill, his donkey and his cat.
«I'm going to take the mill,» said the miller's oldest son.
«I'm going to take the donkey,» said the second.
«And what about me?» asked the youngest son.
«You? You can take the cat,» laughed his brothers.
The young fellow was very much upset. He went out of the house and sat down on the bench.
«Oh, well,» he said in a sad voice. «My brothers have the mill and the donkey. They can put them together and make enough money to live an honest life. But what can I do? I can eat the cat, and I can
make a hat out of his fur. But then I have nothing. I can die of hunger.» The Cat was sitting on the bench too. He was trying not to listen to his master. But of course he heard all his words. And he didn't like them at all. He put on a serious face and said:
«Don't look so sad, Master. I'm not a bad thing. And I am more useful to you alive than dead. I can prove that.»
«How so?» asked the Cat's master. «All you have to do is to give me a bag, and get a pair of boots. Such as gentlemen wear in the woods. I'm going to show you that you're lucky to have me.»
«It's unusual that a cat can speak at all,» the miller's son said to himself. But then he started thinking. «This cat's very good at catching rats and mice. He played so many cunning tricks on them. He never came home without a rat or a mouse. He could hide in the wheat, or pretend to be dead. Perhaps, he can help me after all.»
«OK,» he said to the Cat. «I'm going now to order the boots.»

CHAPTER TWO
The miller's son went to the best shoemaker in town. The shoemaker made elegant shoes and boots for gentlemen.
«I want to order a fine pair of very small boots. They are for my cat,» said the young man.
«OK,» said the shoemaker.
He was not surprised at all. Or, perhaps, just a little.
«Do have any money?» he asked.
«Here you are,» said the miller's son.
He took his last silver coin out of his pocket and gave it to the shoemaker.
Soon the boots were made. The Cat pulled them on. He looked very nice in his elegant boots.
«Don't worry about the money, Master. I'm going to bring you luck,» said the Cat in Boots.
He put the bag around his neck. Cats have no hands, so he held the strings in his forepaws. Then he put some vegetables and a piece of bread into the bag.
The Cat went to the woods. There were many rabbits there. So he lay down, pretending to be dead. The
Cat didn't move at all. His plan was to wait for some foolish rabbit to come and look into his bag.
The Cat didn't wait long. Soon a foolish young rabbit put his head inside the bag. The Cat closed the strings at once and caught him. Then, very proud, he went with the bag to the palace and asked to speak with the King.
The King agreed to see the unusual visitor. The Cat went upstairs to the King's room. He came up to the King and made a low bow. Then he said:
«Sir, here is a nice rabbit from the lands which belong to my noble master, the Marquis of Carabas (he decided to give his young master this title). He told me to offer it to Your Majesty.»
«Tell your master,» said the King, politely, «that I thank him for this nice present. I'm very pleased with his attention.»
Another time the Cat went to a wheat field and hid among standing wheat. He again held his bag open. Soon two fat partridges ran into the bag. The Cat drew the strings, and caught them both.
The Cat went to the King's palace again. He gave the partridges to the King, with the same message from his master as before. The King received the gift. His majesty was very pleased. He even ordered to take the Cat down into the kitchen and give him something to eat and drink.
The Cat enjoyed the meal very much. He sat in the kitchen for a long time, talking about his rich master, the Marquis of Carabas.

CHAPTER THREE
The Cat in Boots continued for two or three months to bring presents to the King. Every time he came to the palace and said, «Your Majesty, here's another present from my master, the Marquis of Carabas.»
Then one day one of the Cat's friends in the palace said to him, «The King wants to drive today in his carriage along the bank of the river. His Majesty is going to take his daughter with him.»
The young princess was a very beautiful girl.
The Cat in Boots said to his master:
«Now you must do what I tell you.»
The miller's son knew nothing about the Cat's new plan. But he was sad and unhappy. That's why he agreed at once.
«Be it so,» he said. «Tell me about your plan.»
«I don't ask much,» said the Cat, looking wise, as cats can. «All you must do is to go and bathe in the river. I know a good place. Then leave the rest to me. Only remember that you are no longer yourself, but the Marquis of Carabas.»
«OK,» said the miller's son, «it's all the same to me.»
He went to the bank of the river, took off his clothes and went bathing. The Cat followed his master and hid his clothes under a great stone.
At that moment the King drove past that place in his carriage. The Cat began to shout at the top of his voice:
«Help! Help! The Marquis of Carabas is drowning!»
The King heard the shouts and put his head out of the carriage. He recognized the Cat.
«Guards!» he said. «Help the Marquis of Carabas! Quick!»
The guards ran to the river. They quickly pulled the young man out of the water.
The Cat came up to the King's carriage. He made a low bow and gave his explanations.
«My master went bathing,» he said, «and suddenly some thieves came. They took all his clothes and ran away. And now the Marquis of Carabas can't appear before Your Majesty and your beautiful daughter.»
«Oh, it's not a problem at all,» said the King.
He ordered one of his guards to ride back to the palace and bring fine clothes for the Marquis of Carabas.
Soon the guard brought a nice suit for the miller's son. The young man put it on and came up to the carriage to thank his majesty.
The miller's son wasn't rich, but he was a handsome and well-built fellow. In the King's elegant suit he looked like a real gentleman.
The beautiful princess admired the handsome young man very much. The miller's son looked at the girl several times, and she fell in love with him.
The King was very happy to meet the Marquis of Carabas. He asked the young gentleman to sit with him and his daughter in the carriage. Of course, the miller's son didn't refuse.

CHAPTER FOUR
The Marquis of Carabas entered the carriage. The Cat in Boots ran away fast. He kept a long way ahead of the King's carriage. He went on and on, till he saw some mowers in a meadow. The Cat came up to them.
«Listen, good people,» he said, in a very firm voice, «the King is going to stop here and talk to you. You must tell him that this meadow belongs to the Marquis of Carabas. Do that if you want to stay alive.»
The King's carriage drove up to the meadow.
«What a nice meadow, and so much hay! Whose meadow is this?» he asked the mowers.
«It belongs to the Marquis of Carabas, sir,» they all cried with one voice, trembling with fear.
«You have a good meadow, marquis,» said his majesty to the miller's son.
The young man bowed and said, «As you see for yourself, this is a very good meadow, sir. The crops of hay are high every year.»
The Cat went still on. He was far ahead of the King and his companions. Finally he came to a wheat field. There were some reapers on the field.
«My good fellows,» he said to the reapers, «the King is going to stop here and talk to you. You must tell him that this field belongs to the Marquis of Carabas. Do that if you want to stay alive.»
The King's carriage arrived a few moments later.
«What a beautiful wheat field! Good people, whose field is this?» he asked the reapers.
«It belongs to the Marquis of Carabas, sir,» cried the reapers, trembling with fear.
At this the King was pleased with the Marquis more than ever.
The King continued his journey, and the Cat still ran on ahead of him. He said the same thing to everyone. The King drove past a new mill, a beautiful garden, houses, more fields and meadows. And all the people on his way said the same: all those places belonged to the Marquis of Carabas.
Finally the Cat returned to the King. He came up to the carriage and bowed.
«Your master is a very rich man,» said the King to the Cat. Then he smiled to the young man and said, «My dear Marquis, isn't this your castle in that park? It looks beautiful. Can we go there now?»
The miller's son didn't know what to say. He looked at the Cat. The Cat bowed and said:
«My master, the Marquis of Carabas, is happy to invite you to the castle. But, Your Majesty, please wait an hour. I'm going to the castle at once to get everything ready for you.»
«No problem,» said the King. «And in the meantime we can visit your nice park. My dear Marquis,» he said to the young man, «I hope you have many flowers there. My daughter is so fond of white roses.»
CHAPTER FIVE
The Cat in Boots ran to the castle. It stood in the middle of a big park. There were wonderful flowers everywhere in the park.
The castle itself was a beautiful high building with small towers. The roofs were red. The walls of the castle were made of white stone. The windows were narrow but high. The rooms on the ground floor had the highest windows. And through the glass visitors could see elegant green curtains.
The castle belonged to a giant. He was the richest giant in the country. All the fields, meadows and woods around the castle were part of his lands. Many people worked for him.
The Cat already knew a lot about the Giant. He was a cruel man. Everyone was terribly afraid of him.
The Cat put on a brave face and went to the castle with his boots on. Soon he arrived at the gate. He asked a servant to speak to the Giant.
«I am a traveller,» he said, «I was not far from here. I couldn't go so near the castle of such a noble gentleman without meeting him.»
The Giant heard this message and agreed to see the visitor. He was going to have dinner, so he was in a good mood.
«Please sit down and have dinner with me,» he said to the Cat.
«Thank you, sir,» said the Cat. «But first I hope you can answer a question. They say that you can change yourself into any animal. A lion, for example, or an elephant.»
«That's true,» said the Giant. «And I can prove it just now. Look! Whom do you see now?»
And the Giant changed himself into a big lion.
The Cat was terribly frightened. He even climbed up the curtain. Of course, it wasn't easy to climb in boots. But the lion was so big! How can you be brave and keep still near such an awful animal?
A few moments later the lion changed back into the Giant. The Cat came down.
«I'm so sorry, sir. I was very frightened,» he said. «But do you know what I think? It was easy for such a big gentleman as you to change yourself into a large animal. But I'm afraid even you can't become a small animal, such as a rat or a mouse. It's just impossible.»
«Impossible!» cried the Giant, very angry. «See how it's impossible!»
At the same moment he changed himself into a mouse. The mouse began to run about the floor.
It was part of the Cat's plan. He jumped on the mouse at once and ate it. So that was the end to the Giant.

CHAPTER SIX
Meanwhile the King, his daughter and the Marquis of Carabas arrived at the castle. The carriage drove over the drawbridge with a loud noise. The Cat heard the noise and ran out into the yard to meet the visitors.
«Welcome, sir, to the castle of the Marquis of Carabas,» he said in a loud voice.
«Your castle is so beautiful, Marquis,» said the King. «Nothing could be finer than this yard and all these buildings. It's not a castle at all. It's a real palace. Let's go inside and look around, if you don't mind.»
The King got out of the carriage and went to the door. The Marquis, without speaking, gave his hand to the princess. As soon as she got out of the carriage, they followed the King.
The King and his companions went through several beautiful rooms and came into a great hall. In the middle of the hall they saw a long table. It was ready for dinner. There were a lot of wonderful things on the table. All of them were the Giant's favourite dishes.
«Why don't we have dinner now?» said the Marquis. «Please sit down.»
The guests took their places. Everyone was hungry, so the dinner started at once.
The King was happy. His daughter was happy too. The girl, in fact, was very much in love with the handsome and polite young man.
His majesty was a practical man, too.
«The marquis is a noble gentleman. My daughter likes him, and he's rich. I think he can make a good husband for my daughter,» he thought after his sixth or seventh glass of wine.
Soon the dinner was over. The King looked across the table at the miller's son.
«Do you like my daughter, marquis?» he said.
«Yes, sir,» said the young man.
«You can marry her then. If you want, of course,» said the King. «That's your choice.»
«I am happy to do that,» said the Marquis of Carabas.
The princess's happy eyes said the same.
The miller's son married the King's daughter the next day. The young man was happy. He was a rich noble gentleman now. The Giant's castle belonged to him. He had all the Giant's lands, too. And he had a beautiful wife.
The Cat in Boots became at once a great lord. Of course, he stayed in the castle with the marquis and the princess. He ordered more elegant boots for himself. But he never ran after mice any more, except for pleasure.

Типичные ошибки начинающих программистов

Не так давно пробовал устраиваться на работу тестировщиком Java(мой текущий уровень — 19). Получил следующий фидбек:

К сожалению, есть ошибки в задании. Ниже фидбек от нашего специалиста:

Неявная логика в методах
Отсутствие иерархии, неумение сравнивать объекты по типу
Недостаточное знакомство с базовыми вещами в Java
Исользование громоздких конструкторов вида CLEANER (false, false, true, false, false, false, false)
Спагетти-код там, где можно было упростить логику

Соль в том, что моя программа выполняет все требования. которые были описаны в ТЗ. Для ее описания мне хватило тех знаний Java, которые на данный момент есть. Но не хватило чего-то другого. Как с этим бороться? Может, я делаю что-то не так? Мне стоит что-то перечитать или что-то сделать? Моя проблема, как и многих начинающих программистов, не в том, что я чего-то не знаю, а что не умею обращаться с тем, что знаю. Все задачи решал до этого, серьезных проблем не возникало.

Если кому-то интересен мой код — github.com/vozni4iy/office