CodeGym/Java Course/Module 1 no mu/生活小竅門:如何更好更快地編寫代碼

生活小竅門:如何更好更快地編寫代碼

開放

1. 表達式 vs 語句

在 Java 中,區分兩類是有幫助的:語句表達式。語句通常被稱為被執行,而表達式被稱為被求值。但這不是最重要的。

語句和表達式之間的主要區別是計算表達式有一個結果。這個結果有一個類型,它可以賦值給一個變量或者用在其他一些表達式中。

例子:

代碼 筆記
int x; 陳述
(a < 10) 類型為的表達式boolean
i++; i類型與變量類型相同的表達式
x = 5; x類型與變量類型相同的表達式

這給了我們什麼?

首先,我們可以利用這樣一個事實,即許多語句實際上是表達式(意味著它們的計算結果是一個值)。例如,像這樣的代碼將起作用:

代碼 筆記
int x, y, z;
x = y = z = 1;
int x, y, z;
x = (y = (z = 1))

其次,如果我們願意,我們可以忽略計算表達式的結果。

代碼 我們忽略結果的代碼:
int x = scanner.nextInt();
boolean m = (5 < 10);
scanner.nextInt();
(5 < 10);

我們忽略計算表達式的結果,例如,如果表達式涉及做一些有用的事情,而這個動作對我們來說很重要,而不是結果本身。


2.三元運算符

這個生活黑客已經​​比上一個更有趣了。Java 有一個特殊的三元 運算符。它的語法有點類似於語句的語法if-else

Condition ? Expression 1 : Expression 2;

如果條件為真,則計算表達式 1 ,否則計算表達式 2 。條件後跟一個問號,兩個表達式用冒號分隔。

三元運算符和語句的主要區別在於if-else三元運算符是一個表達式,這意味著我們可以將其結果賦值給某物。

例如,假設我們要計算兩個數中的最小值。使用三元運算符,此代碼將如下所示:

int a = 2;
int b = 3;
int min = a < b ?  a : b;

或者,假設您需要根據某些條件為變量分配不同的值。你是怎樣做的?

一種選擇是使用if-else語句:

int age = 25;
int money;
if (age > 30)
   money = 100;
else
   money = 50;

第二種選擇是使用三元運算符,即if-else語句的簡寫:

int age = 25;
int money = age > 30 ? 100 : 50;

那麼哪個更好用——if-else語句還是三元運算符?就執行速度而言,沒有太大區別。這更多是代碼可讀性的問題。而這是非常重要的一點:代碼不僅要能正確運行,而且要便於其他程序員閱讀。

最簡單的規則是:如果代碼適合一行,則使用三元運算符;但如果它不適合一行,那麼最好使用一個if-else語句。



3.比較實數

如前所述,您不能只獲取實數並進行比較。總是有可能丟棄一些有效數字,從而導致意想不到的副作用。

這就是為什麼有一個經過時間考驗的方法。如果兩個實數相差非常小的值,則可以認為它們相等。例子:

double a = 1.000001;
double b = 1.000002;
if ( (b - a) < 0.0001 )
   System.out.println("The numbers are equal");
else
   System.out.println("The numbers are not equal");

但這並不是我們需要擔心的全部,因為數字之間的差異很可能會變成負數。因此,要使這種方法起作用,您不僅需要比較數字之間的差異,還需要比較數字之間差異的絕對值:|a-b|

Java有一種計算數字絕對值的方法Math.abs()::

int m = Math.abs(value);

因此,我們上面示例的更正版本將如下所示:

double a = 1.000001;
double b = 1.000002;

if ( Math.abs(b - a) < 0.0001 )
   System.out.println("The numbers are equal");
else
   System.out.println("The numbers are not equal");

2
任務
Java Syntax,  等級 4課堂 4
上鎖
Good or bad?
Student robot Peter is an overachiever. Previously, his server was configured to receive scores on a five-point scale, but now his teachers have switched to a 12-point scale. But Peter doesn't know this. He's still focused on getting fives. Let's write him a compare method that compares any number with five.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Closest to 10
Ten is extremely popular and attractive number. Everyone wants to be a ten. Or at least as close to it as possible. Two numbers are standing around wondering which of them is cooler. Answer: whichever is closer to ten. Let's write these numbers a displayClosestToTen method that will determine which of them is cooler.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Come on, lucky seven!
Dice games are popular on the planet Foggy Multidimensions. The rules are different than the Earth version: Multidimensionals perceive far more dimensions than primitive three-dimensional earthlings. Their die has 4294967295 faces. Players win only if they roll a number between 50 and 100. We'll write a method that checks whether the die roll is in this range.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Seasons on Terra
An Earth year consists of four seasons, each of which lasts 3 months. While our ship was parked on this cradle of humanity, the Interplanetary Tax Service asked us to write a program to determine the season based on a number corresponding to the month of the year. We don't know why they want it. They say that it's none of our business. But they promised not to remain in our debt.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Positive and negative numbers
Diego is tall, but Alfredo is short. Rishi is experienced, but you're a "noob" programmer. Comparisons are unavoidable in life. And the same thing is true in programs. So we'll continue practicing comparisons and displaying stuff on the screen. This time let's compare the entered number with zero and manipulate it based on the result of the comparison.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Day of the week
Planet Terra still has "offices"—an outdated type of workspace. With current technology, there is no need for them, but earthlings tend to be nostalgic and haven't been in a hurry to eradicate them. Terrestrial office workers develop "TGIF syndrome": they constantly want to know what day of the week it is. Let's write a program for them!
8
任務
Java Syntax,  等級 4課堂 4
上鎖
Number of days in the year
On Earth, a year lasts 365 or 366 days. The number of days is calculated according to the following formula: A leap year (366 days) is every year evenly divisible by 4, except for years that are multiples of 100 but not multiples of 400. We'll write a program that will determine whether the user has entered a leap-year or ordinary year from the keyboard.
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Rule of the triangle
Can any three line segments be the sides of a triangle? You probably already guessed (or remembered from high-school geometry) that you can only have a triangle if the sum of the lengths of any two sides is greater than the length of the third side. Well, now we're going to write code to check whether 3 line segments are suitable for forming a triangle.
8
任務
Java Syntax,  等級 4課堂 4
上鎖
Crossing the road blindly
Let's say that we are certain that at the beginning of every hour our traffic light is green for 3 minutes, yellow for a minute, and then red for another minute. Then the sequence repeats. Our program must determine what light is on now (where "now" is a real number that indicates the number of minutes that have elapsed since the beginning of the hour).
4
任務
Java Syntax,  等級 4課堂 4
上鎖
Do we have a pair?
Suppose we have three numbers. Now let's imagine that they are not numbers, but people ... Actually, never mind about that. We don't need to make this weird. Let's just check if there is at least one pair of identical numbers among the three. If there is, we'll display it on the screen. And if the three numbers are the same, we'll display all three.
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言