用 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 人檢視

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告