简体   繁体   English

从main中的方法打印数组

[英]Printing an array from method in main

i have an array returned from method, its like {2,2,3,5,0,0,0,0} and i want to print it to output from main like: 2*2*3*5 , how can I do this ? 我有一个从方法返回的数组,像{2,2,3,5,0,0,0,0} ,我想将其打印以从main输出,例如: 2*2*3*5 ,我怎么能做这个 ? Here's my code: 这是我的代码:

RozkladLiczby a=new RozkladLiczby(Integer.parseInt(args[0]));
System.out.println(Arrays.toString(a.czynnikiPierwsze(Integer.parseInt(args[i]))));

When i use Arrays.toString() I get output like {2,2,3,5,0,0,0,0} . 当我使用Arrays.toString()我得到类似{2,2,3,5,0,0,0,0}输出。

How can I get it like I wrote before? 我怎样才能像以前写的那样得到它? RozkladLiczby is creatig a array of ints and czynnikiPierwsze method is returning an array. RozkladLiczby正在创建一个整数数组,而czynnikiPierwsze方法正在返回一个数组。

You could iterate over your array to print it in the way you want. 您可以遍历数组以所需方式打印它。 Have a look into the Arrays.toString() method source code to get an idea on how to do that. 查看Arrays.toString()方法的源代码,以获取有关如何执行此操作的想法。

It should look like something: 它应该看起来像:

int[] arr = a.czynnikiPierwsze(Integer.parseInt(args[i])))
   for (int i = 0; i < arr.length; i++) {
      if (i > 0) {
          System.out.println("*");
      }
   System.out.println(arr[i]);
}

You could just do : 您可以这样做:

import java.util.Arrays;

public class PrintArray{

 public static void main(String []args){
    String g = Arrays.toString(a.czynnikiPierwsze(Integer.parseInt(args[i])));
    g = g.replace(", 0","");
    g = g.replace(", ","*");
    g = g.replace("[","");
    g = g.replace("]","");
    System.out.println(g);
 }

} }

INPUT : {2,2,3,5,0,0,0,0} 输入:{2,2,3,5,0,0,0,0}

OUTPUT : 2*2*3*5 输出:2 * 2 * 3 * 5

Try something like this: 尝试这样的事情:

   String s = "";
    for (int n : myArray){
     s += n + "*";
    }

Being myArray the array of int you have. 作为myArray您拥有的int数组。 In case myArray is {2,2,3,5,0,0,0,0} this will print out: 如果myArray{2,2,3,5,0,0,0,0}则将输出:

2*2*3*5*0*0*0*0*

You have to take into account the checking for the last element of the array if you don't want to print * after the last element. 如果您不想在最后一个元素之后打印* ,则必须考虑检查数组的最后一个元素。

Here is an example for printing w/o 0 digits. 这是打印不带0位数字的示例。

public class Main {

    static int a[] = {1,2,3,4,5,6,0,0,0,0};

    public static void main(String args[]){

        for(int i=0; i<a.length; i++){
            if(a[i]!=0)
                System.out.print(a[i]+"*");    

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM