我想使用 for 循环整齐地打印一个一维数组。(Java)

huangapple go评论71阅读模式
英文:

I want to print a 1-dimensional array using a for loop neatly. (java)

问题

我正试图打印一个一维数组,并以清晰标记的输出形式呈现出来。我有一个不带参数的方法,用于打印这个一维数组,到目前为止,我已经创建了一个循环,它从id[0]到id[n-1]打印了数组的内容。我想要完成的主要任务是在我的主方法中,我调用显示一个数组的方法 3 次。输出需要清楚地定义每次调用的结果。例如:部分 A 的结果:(43,45,43,4,5,)。我应该使用 printf,或者我应该如何解决这个问题?我已经尝试在这个网站上查找了一段时间,但是没有找到足够具体的内容来帮助我。

到目前为止,我有:

public void displaySubsets(){

   for(int i : array) {
   System.out.print("(");
   System.out.print(array[i]);
   System.out.print(")");
}
英文:

I am trying to print a 1-dimensional array in a clearly labeled output presentation. I have a method that takes no arguments to print the one-dimensional array, and so far I've created a for loop that prints the contents of the array from id[0] to id[n-1]. The main task I want to accomplish is in my main method I call the method that displays an array 3 times. The output needs to clearly define the results for each call. Ex: Results for part A : (43,45,43,4,5,). Should I use printf or how should I approach the problem. Tried looking on this site for a while, but couldn't find anything specific enough to help.

So far I have

public void displaySubsets(){

   for(int i : array) {
   System.out.print("(");
   System.out.print(array[i]);
   System.out.print(")");

}

答案1

得分: 2

你只需执行以下操作:

System.out.println(Arrays.toString(array));

或者如果你想自己编写代码(假设数组不为空或为null):

System.out.print("(" + array[0]);
for (int i = 1; i < array.length; i++) {
   System.out.print(", " + array[i]);
}
System.out.println(")");
英文:

You can just do the following:

System.out.println(Arrays.toString(array));

or if you want to roll your own. (assumes the array is not empty or null).

System.out.print(&quot;(&quot; + array[0]);
for (int i = 1; i &lt; array.length; i++) {
   System.out.print(&quot;, &quot; + array[i]);
}
System.out.println(&quot;)&quot;);  

</details>



# 答案2
**得分**: 0

## 以下是一种实现方法:

遍历数组并将数字拼接到新的字符串变量中。

```java
  static void printArray(){
    String printFormat = "";
    System.out.println("数组长度: " + array.length);
    //遍历数组
    for (int i=0; i < array.length; i++) {
      if (i+1 == array.length){
        //如果是数组中的最后一个值,我们不想添加", "
        //将数组的值拼接到新的字符串中,不带", "
        printFormat = printFormat + array[i];
      }else{
        //将数组的值拼接到新的字符串中
        printFormat = printFormat + array[i] + ", ";
      }
    }
    System.out.println("部分 A 的结果 : (" + printFormat + ")");
  }

点击这里运行代码

英文:

Here is one way of doing it:

Iterate over the array an concatenating the numbers into a new string variable.

  static void printArray(){
    String printFormat = &quot;&quot;;
    System.out.println(&quot;Array Length: &quot; + array.length);\
    //iterate over the array
    for (int i=0; i &lt; array.length; i++) {
      if (i+1 == array.length){
        //If is the last value in the array we don&#39;t want to add the &quot;, &quot;
        //concatenate the array&#39;s value into a new string without &quot;, &quot;
        printFormat = printFormat + array[i];
      }else{
        //concatenate the arrays value into a new string
        printFormat = printFormat + array[i] +&quot;, &quot;;
      }
    }
    System.out.println(&quot;Results for part A : (&quot; + printFormat + &quot;)&quot;);
  }

Click here to run the code

答案3

得分: 0

有不止一种方法可以做到:

我会选择我们的朋友“Java 8 Streams”,具体来说是Arrays类的stream()方法。它使代码更加优雅,直观且高效。

package com.example;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr[] = { 43, 45, 43, 4, 5 }; 
        System.out.print("(");
        Arrays.stream(arr)
              .forEach( e -> System.out.print(e + ",") );
        System.out.println(")");
    }
}

> 输出:(43,45,43,4,5,)

英文:

There's more than 1 way to do it:

I would opt for our friend "Java 8 Streams", more specifically the stream() method of Arrays class. It makes it elegant, intuitive and efficient.

package com.example;

import java.util.Arrays;

public class Main {
	public static void main(String[] args) {
		int arr[] = { 43, 45, 43, 4, 5 }; 
		System.out.print(&quot;(&quot;);
		Arrays.stream(arr)
		      .forEach( e -&gt; System.out.print(e + &quot;,&quot;) );
		System.out.println(&quot;)&quot;);
	}
}

> Output: (43,45,43,4,5,)

答案4

得分: 0

有很多方法可以解决这个问题。

替代方案1

你可以这样做:

System.out.println(Arrays.toString(array));

就像其他人提到的那样。

替代方案2

public static void main(String[] args) {
    Main main = new Main();
    int array[] = {43, 45, 43, 4, 5};
    System.out.println(main.printArray(array));
}

public String printArray(int[] array) {
    StringBuilder builder = new StringBuilder();
    builder.append("(");

    for (int i : array) {
        builder.append(i);
        builder.append(", ");
    }

    builder.append(")");
    return builder.toString();
}

在打印方面,我喜欢使用 StringBuilder,因为它比直接使用 System.out.println() 更快。

希望对你有用!

英文:

There are many ways you can solve this.

Alternative 1

One way you can do this is just do:

System.out.println(Arrays.toString(array));

Like other mentioned.

Alternative 2

public static void main(String[] args) {
   Main main = new Main();
   int array[] = {43,45,43,4,5};
   System.out.println(main.printArray(array));
 }

public String printArray(int[] array){
    StringBuilder builder = new StringBuilder();
    builder.append(&quot;(&quot;);
    
    for(int i : array){
        builder.append(i);
        builder.append(&quot;, &quot;);
    }
    
    builder.append(&quot;)&quot;);
    return builder.toString();
}

I like to use StringBuilder when it comes to printing because it's faster than just doing System.out.println().

Hope it was useful!

huangapple
  • 本文由 发表于 2020年8月31日 07:42:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63663129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定