用 Java 编写程序将数组转换为字符串?


java.util 包的 Arrays 类提供一个名为 toString() 的方法,该方法接受一个数组值(任何类型)并返回一个 String。

示例

下列 Java 程序接受用户输入的各种数组,将它们转换为 String 值并打印结果。

 实际演示

import java.util.Arrays;
import java.util.Scanner;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      //Integer array to String
      System.out.println("Enter 5 integer values: ");
      int intArray[] = new int[5];
      for(int i=0; i<5; i++){
         intArray[i] = sc.nextInt();
      }
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
      //float array to String
      System.out.println("Enter 5 float values: ");
      float floatArray[] = new float[5];
      for(int i=0; i<5; i++){
         floatArray[i] = sc.nextFloat();
      }
      System.out.println("Contents of the float array: "+Arrays.toString(floatArray));
      //double array to String
      System.out.println("Enter 5 double values: ");
      double doubleArray[] = new double[5];
      for(int i=0; i<5; i++){
         doubleArray[i] = sc.nextDouble();
      }
      System.out.println("Contents of the double array: "+Arrays.toString(doubleArray));
      //byte array to String
      System.out.println("Enter 5 byte values: ");
      byte byteArray[] = new byte[5];
      for(int i=0; i<5; i++){
         byteArray[i] = sc.nextByte();
      }
      System.out.println("Contents of the byte array: "+Arrays.toString(byteArray));
      //char array to String
      System.out.println("Enter 5 character values: ");
      char charArray[] = new char[5];
      for(int i=0; i<5; i++){
         charArray[i] = sc.next().toCharArray()[0];
      }
      System.out.println("Contents of the char array: "+Arrays.toString(charArray));
      //object array to String
      System.out.println("Enter 5 String values: ");
      Object objArray[] = new Object[5];
      for(int i=0; i<5; i++){
         objArray[i] = sc.next();
      }
      System.out.println("Contents of the object array: "+Arrays.toString(objArray));
   }
}

输出

Enter 5 integer values:
14
12
63
78
96
Contents of the integer array: [14, 12, 63, 78, 96]
Enter 5 float values:
2.1
3.2
14.3
6.1
3.2
Contents of the float array: [2.1, 3.2, 14.3, 6.1, 3.2]
Enter 5 double values:
1254.3256
1458.2354
1478.24
14587.325
1457.325
Contents of the double array: [1254.3256, 1458.2354, 1478.24, 14587.325, 1457.325]
Enter 5 byte values:
1
25
61
11
24
Contents of the byte array: [1, 25, 61, 11, 24]
Enter 5 character values:
a
b
c
d
e
Contents of the char array: [a, b, c, d, e]
Enter 5 String values:
hello
hi
bye
welcome
thankyou
Contents of the object array: [hello, hi, bye, welcome, thank you]

更新时间: 30-Jul-2019

296 人查看

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.