“很久以前,計算機只能顯示文本。程序在接收到鍵盤輸入後在屏幕上顯示數據。這稱為“控制台用戶界面”或簡稱為“控制台”。窗口界面是控制台的替代方案。隨著這種類型的界面,用戶通過一個或多個窗口與程序交互。由於我們只是在學習如何編程,所以我們將從使用控制台開始。”

“好的。”

“文本在控制台(屏幕)上連續顯示,一行一行。文本是使用鍵盤輸入的。為了避免錯誤,鍵盤輸入顯示在屏幕上。有時看起來像人類用戶和程序輪流在屏幕上寫東西。

“可以使用System.out.print ()方法在屏幕上顯示文本。該方法只是簡單地顯示文本,而System.out.println ()顯示文本並將光標移動到下一行。”

代碼 結果
System.out.print("Rain");
System.out.print("In");
System.out.print("Spain");
雨在西班牙
System.out.print("Rain");
System.out.println("In");
System.out.print("Spain");

在西班牙
System.out.println("Rain");
System.out.println("In");
System.out.println("Spain");


西班牙

“為了將文本分開,我們需要添加一個空格。例如:”

代碼 結果
int a = 5, b = 6;
System.out.print(a);
System.out.print(b);
56
int a = 5, b = 6;
System.out.print(" " + a + " " + b);
 5 6
int a = 5, b = 6;
System.out.print("The sum is " + (a + b));
The sum is 11

“知道了”

“這使您可以在屏幕上顯示任何內容: 所有 Java 對像都可以轉換為字符串。所有 Java 類都派生自 Object 類,該類具有 toString() 方法。當您想將對象轉換為字符串時調用此方法細繩。”

代碼 描述
Cat cat = new Cat("Oscar");
System.out.println("The cat is " + cat);
這三個例子是等價的。
Cat cat = new Cat("Oscar");
System.out.println("The cat is " + cat.toString());
Cat cat = new Cat("Oscar");
String catText = cat.toString();
System.out.println("The cat is " + catText);
3
任務
Java Syntax,  等級 3課堂 3
上鎖
Display right away
Programming isn't always difficult. Sometimes you need to do simple tasks. And the more similar tasks you have to do, the more you want to automate them. Let's implement one more method. Ultimately, objects without methods don't do anything. We'll pass the string s to the method, which will then display it on the screen.

“但是我的程序顯示‘ The cat is com.codegym.lesson3.Cat@1fb8ee3 ’。這到底是什麼意思?”

“Object 類的標準 toString() 方法返回一個由類名對象的內存地址(十六進制形式)組成的字符串。”

“嗯嗯。這種方法能有什麼好處呢?”

“你可以在你的類中編寫你自己的 toString() 實現。然後就是將要調用的方法。”

“真的嗎?好吧。”

“這是迭戈的一些任務。”

3
任務
Java Syntax,  等級 3課堂 3
上鎖
Currency exchange
Loan sharking, sales, banking: do you have a backup plan if programming doesn't work out? No? In that case, let's help traders and financiers with our top-notch programs. First, we'll organize a currency exchange: write a program that converts euros to dollars at a given exchange rate.
3
任務
Java Syntax,  等級 3課堂 3
上鎖
Task with percentages
If you weren't afraid of problems with percentages in school, then this problem won't scare you either. But if you do suddenly find yourself afraid, it's time to face your fear and realize that this is actually a simple and pleasant topic. Let's implement a method that increases the passed integer by 10 percent.
1
任務
Java Syntax,  等級 3課堂 3
上鎖
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).