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 ? 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}
.
How can I get it like I wrote before? RozkladLiczby
is creatig a array of ints and czynnikiPierwsze
method is returning an array.
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.
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}
OUTPUT : 2*2*3*5
Try something like this:
String s = "";
for (int n : myArray){
s += n + "*";
}
Being myArray
the array of int
you have. In case myArray
is {2,2,3,5,0,0,0,0}
this will print out:
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.
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]+"*");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.