获取多个字符串数组并将其写入单行打印

时间:2019-02-21 03:03:09

标签: java

我想知道是否可以将所有字符串数组的结果打印到单个println中而不是多个上。

    String[] test1 = { "a", "b", "c" };  
    String[] test2 = { "a", "B", "c", "D", "e" }; 
    String[] test3 = { "A", "B", "C", "D" };  
    String[] test4 = { "$", "B", "c", "6", "D", "\n", "E" };  

    int upperCaseCount1 = countUppercase(test1); //Instead of printing this
    System.out.println(upperCaseCount1);
    int upperCaseCount2 = countUppercase(test2);
    System.out.println(upperCaseCount2); 
    int upperCaseCount3 = countUppercase(test3);
    System.out.println(upperCaseCount3);
    int upperCaseCount4 = countUppercase(test4);
    System.out.println(upperCaseCount4);

    //am i able to use a single line print? like....my failed attempts here.
    System.out.println(countUppercase("test1", "test2","test3", "test4"); 

1 个答案:

答案 0 :(得分:1)

您可以将结果连接到println

int upperCaseCount1 = countUppercase(test1);
int upperCaseCount2 = countUppercase(test2);
int upperCaseCount3 = countUppercase(test3);
int upperCaseCount4 = countUppercase(test4);

System.out.println( upperCaseCount1 +", "+upperCaseCount2 +", "+upperCaseCount3 +", "+upperCaseCount4); 

如果您可以使用printf,也可以执行以下操作:

System.out.printf( "Results: %d, %d, %d, %d%n", upperCaseCount1, upperCaseCount2, upperCaseCount3, upperCaseCount4); 

%d用于int,%n是新行。 simple tutorial

您还可以使用StringBuilder。 tutorial

StringBuilder builder = new StringBuilder("Results: ");
builder.append(countUppercase(test1)).appende(" ").
    append(countUppercase(test2)).appende(" ").
    append(countUppercase(test3)).appende(" ").
    append(countUppercase(test4));
System.out.println( builder);