Java 程序打印字符串

javaobject oriented programmingprogramming更新于 2024/4/11 1:16:17

在本文中,我们将了解如何在 Java 中打印字符串。字符串是字符和字母数字值的模式。创建字符串的最简单方法是写入 −

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

每当在代码中遇到字符串文字时,编译器都会创建一个 String 对象,其值在本例中为 "Welcome to the club!!!&39;。

与任何其他对象一样,您可以使用 new 关键字和构造函数创建 String 对象。String 类有 11 个构造函数,允许您使用不同的来源(例如字符数组)提供字符串的初始值。

在 Java 编程语言中,字符串被视为对象。Java 平台提供 String 类来创建和操作字符串。 String 类是不可变的,因此一旦创建 String 对象就无法更改。如果有必要对字符串进行大量修改,请使用 String Buffer 和 String Builder 类。

输入

假设我们的输入是 −

Hello my name is John!

输出

所需的输出将是 −

字符串是:
Hello my name is John!

算法

步骤 1- 开始
步骤 2- 声明一个字符串
步骤 3- 提示用户输入一个字符串/在变量中定义该字符串
步骤 4- 读取值
步骤 5- 在控制台上显示它
步骤 6- 停止

示例 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!

相关文章


有用资源