Java 程式列印字串


在本文中,我們將瞭解如何在 Java 中列印字串。字串是由字元和字母數字值組成的模式。建立字串最簡單的方法是編寫 -

String str = "Welcome to the club!!!"

每當它在你的程式碼中遇到字串字面量時,Java 編譯器 會建立一個 String 物件,其值為在這種情況下,“Welcome to the club!!!”。

與任何其他物件一樣,您可以使用 new 關鍵字和建構函式建立 String 物件。String 類有 11 個建構函式,允許您使用不同的源(例如字元陣列)來提供字串的初始值。

Java 程式語言中,字串被視為物件。Java 平臺提供String 類來建立和操作字串。String 類是不可變的,因此一旦建立了 String 物件,就不能更改它。如果需要對字元字串進行大量修改,則使用 StringBuffer 和 StringBuilder 類。

輸入

假設我們的輸入為 -

Hello my name is John!

輸出

所需的輸出將為 -

The string is:
Hello my name is John!

演算法

Step 1- START
Step-2- Declare a string
Step 3- Prompt the user to enter a string/ define the string in a variable
Step 4- Read the value
Step 5- Display it on the console
Step 6- STOP

示例 1

在這裡,輸入是根據提示由使用者輸入的。您可以在我們的程式碼執行工具 執行按鈕中即時嘗試此示例。

import java.util.Scanner;
public class PrintString {
   public static void main(String[] args){
      String my_str;
      System.out.println("The required packages have been imported ");
      Scanner my_scan = new Scanner(System.in);
      System.out.print("A scanner object has been defined \n");
      System.out.print("Enter a string:");
      my_str = my_scan.nextLine();
      System.out.print("The nextLine method is used to read the string");
      System.out.println("The string is: ");
      System.out.println(my_str);
   }
}

輸出

Required packages have been imported
A scanner object has been defined
Enter a string: Hello my name is John!
The nextLine method is used to read the stringThe string is:
Hello my name is John!

示例 2

public class PrintString{
   public static void main(String[] args){
      String my_str;
      System.out.println("The required packages have been imported ");
      my_str = "Hello my name is John!";
      System.out.println("The string is: ");
      System.out.println(my_str);
   }
}

輸出

The required packages have been imported
The string is:
Hello my name is John!

更新於: 2024-06-14

17K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告