Adding zero to a single digit number, Is it possible?

后端 未结 2 705
情话喂你
情话喂你 2021-01-14 02:43
public class MultiplicationTable {
public static void main (String[]a){

    int[] x;
    x = new int[10];
    int i;
    int n=0;

    for (i=0;i

        
相关标签:
2条回答
  • 2021-01-14 03:03

    Yes you can! You can use String.format to add zero padding to your output.

    Example:

    String.format("%05d", 2) would produce 00002.

    Some improvement on the current code:

    I'm not sure why you intend to store the numbers inside an array (for practice purpose maybe), but that is not necessary as it goes from 1 to 10 anyway. Though if you want to do that, you don't need both i and n.

    for (i=0; i<x.length; i++){
        x[i] = i+1;
        System.out.print(x[i] + " ");
    }
    

    Secondly, I'm sure you realize that you have a lot of duplicate code, and it's quite sequential. You can do that using 2 nested for loops, instead of having 10 single loops:

    for (int row = 1; row <= 10; row++) {
        for (int col = 1; col <= 10; col++)
            System.out.print(String.format("%03d", row * col));
        System.out.println();
    }
    
    0 讨论(0)
  • 2021-01-14 03:04

    Yes:

    String.format("%01d", x[i]*x[j]); is what you want.
    

    If you're familiar with printf in C then this will be familiar. If not, read the java reference on String.format format strings.

    Also, rather than 10 System.out.println statements, you can use a doubly nested loop with two counters. One to count which row you're in j and one for each column i.

    0 讨论(0)
提交回复
热议问题