Документация с комментариями
Введено
15:05
Использование объектов и методов
Вот две программы Java. В первой отсутствует точка с запятой. Вторая делит семь на два и сохраняет ответ в целочисленной переменной. Компилятор останавливает…
Озвучивание на английском · переключаемые субтитры на английском и китайском языках
В этом уроке
| English | Значение |
|---|---|
| comment/ˈkɒment/ | комментарий |
A comment does not repair an active formula
- For price 100,
total = price * 10 / 100;calculates 10 even if a comment 注释 says “amount paid after ten percent off”. Editing that explanation does not make the expression calculate 90. - Change the active expression to
price * 90 / 100to calculate the intended payment in this whole-number example. Comments can reveal an intended policy; verify the code implements it.

Identify text that is excluded from code
//starts a comment ending at the line break./*starts a block comment ending at the next*/; block comments do not nest. Delimiters inside string literals are text, so"https://example.com"does not start a comment.- Comment text is not executed as Java statements. Adding a separate explanation leaves the active expression unchanged; placing
//before an active assignment removes that assignment from the compiled code and can change behavior.
Put Javadoc tags on separate lines
- A
/** ... */documentation comment immediately before a declaration can be processed by Javadoc. Its summary explains the operation; block tags such as@paramand@returnstart their own lines after optional whitespace and*. - The complete class below documents a non-negative radius and returns its circle area. The tags describe inputs, outputs and a rejected input; a comment alone does not enforce the precondition, so the method explicitly checks negative radii.
/** Circle-area calculations for finite radii. */
public class AreaDoc {
/**
* Returns the area of a circle for a finite radius.
* @param r the non-negative radius
* @return the area in squared radius units
* @throws IllegalArgumentException if r is negative
*/
public static double area(double r) {
if (r < 0) {
throw new IllegalArgumentException("Negative radius");
}
return Math.PI * r * r;
}
}

Javadoc распознает @param как блочный тег, когда он встроен после текста сводки в той же строке.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Блочный тег начинается с новой строки после optional whitespace и опциональной ведущей звездочки. Используйте показанный многострочный комментарий.
Explain the decision a reader cannot see
- A useful discount comment might state “payment is 90% of the listed price; this exercise uses whole-number prices”. This explains policy and assumptions, while
// multiply by 90merely repeats an operation. - A summary of a public method is useful even when its body is short: callers need its contract without studying the implementation. Prefer explanations that supply missing context rather than declaring every descriptive comment redundant.
Когда программа Java выполняется, комментарии...
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Комментарии предназначены для людей — Java игнорирует их.
Что начинает однострочный комментарий в Java?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
// продолжается до конца строки; /* */ — это блочный комментарий.
Какой стиль комментариев инструменты превращают в документацию API?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Javadoc /** */ с @param/@return генерирует документацию API.
Добавление поясняющего комментария рядом с неизмененной активной формулой исправляет её вычисление.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Неверно: поясняющие комментарии не являются операторами. Закомментирование оператора может изменить поведение, но это изменяет только то, какой код является активным.
Хорошие комментарии объясняют ЗАЧЕМ, а не повторяют, что код явно делает.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Комментируйте намерения, а не очевидное.
Check documentation against implementation
- Suppose the comment promises that negative radii are rejected, but the guard is deleted. The documentation is now false even though it still generates successfully; test the negative input as well as an ordinary radius.
- When behavior changes, update the implementation, its checks and its documentation together. Generating an API page verifies documentation syntax, not the truth of every claim in it.
/** Returns an area. @param r radius @return area */ does not put the block tags at the required starts of lines. Use the multiline form above, then inspect the generated parameter and return sections. Ordinary explanatory comments are not executable repairs.
Полезный комментарий или нет?
Хорошие комментарии объясняют намерения, а не очевидное. Отсортируйте каждый из них.
Predict a commented-out assignment
- Start with
int x = 1;. With activex = 5;, printing x gives 5; replacing that line with// x = 5;prints 1. Changing which statements are active differs from adding a note beside an unchanged statement. - Review three questions separately: is the active calculation correct, does the comment accurately explain it, and are the Javadoc tags parsed into their intended sections? A successful compile does not answer all three.
Comments explain code to readers. Delimiters can exclude statements, while notes beside active code do not fix calculations. Javadoc block tags begin on separate lines; keep the documented contract consistent with the implementation.
For a price of 100, type the amount paid after a ten percent discount.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
The intended payment is 100−10=90. The misleading comment does not make the original expression calculate 90.
int x = 1; за этим следует // x = 5; в отдельной строке. Какое значение x будет выведено?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Присваивание 5 исключается однострочным комментарием; x остается равным 1.
Что пошло не так? Это увидит только команда сайта.