Java 程序:布尔值转换为字符串


2022年2月9日, Learn eTutorial
1202

在这里,我们将解释如何编写 Java 程序将布尔值转换为字符串。

如何在 Java 中将布尔值转换为字符串?

在 Java 中,可以使用 **Boolean().toString** 函数将布尔值转换为字符串。示例如下。

 String s = new Boolean(bln).toString();

这里 **bln** 是布尔变量,**s** 是字符串变量。布尔变量 **bln** 被转换为字符串变量 **s**。

如何在 Java 中实现将布尔值转换为字符串的 Java 程序?

首先,我们需要声明 **BtoS** 类。创建 Scanner 类的对象 **sc**。从用户读取布尔变量到变量 **bn**。使用 Java 中的 **Boolean().toString()** 函数将 **bn** 转换为字符串。该函数返回与布尔变量 **bn** 等效的字符串值。然后使用 Java 中的 `system.out.println()` 显示布尔值 **bn**。

算法

步骤 1:使用 **public** 修饰符声明 **BtoS** 类。

步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始

步骤 3:创建 Scanner 类的对象 **sc**。

步骤 4:使用 **sc.nextBoolean()** 从用户读取布尔值到变量 **bn**。

步骤 5:使用 **Boolean(bn).toString()** 将布尔值转换为字符串。

步骤 6:显示 **bn** 的字符串等效值 **str**。

Java 源代码

                                          import java.util.Scanner;
public class BtoS{  
   public static void main(String args[]){  
   Scanner sc = new Scanner(System.in);
   System.out.println("Enter the boolean value");
   boolean bn = sc.nextBoolean();
   String str = new Boolean(bn).toString();
    
 System.out.println("The string equivalent of "+bn+ " is "+str);  
   }
}
                                      

输出

Enter the boolean value
true
The string equivalent of true is true