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

java 8object oriented programmingprogramming更新于 2025/9/5 15:08:17

 java.util  包中的 Arrays 类提供了一个名为 toString() 的方法,该方法接受一个数组值(任意类型)并返回一个字符串。

示例

以下 Java 程序从用户那里接受各种数组,将它们转换为字符串值并打印结果。

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]

相关文章