Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Java将此数字表打印到控制台?_Java - Fatal编程技术网

如何用Java将此数字表打印到控制台?

如何用Java将此数字表打印到控制台?,java,Java,要求输入自然数n,我希望以以下格式打印到控制台: 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 . . . n . . . 5 4 3 2 1 输入4,这是我到目前为止得到的: 1 21 321 4321 我想在数字之间加一个空格。这是我的代码: import java.util.

要求输入自然数n,我希望以以下格式打印到控制台:

                1
              2 1
            3 2 1
          4 3 2 1
        5 4 3 2 1
          .
          .
          .
n . . . 5 4 3 2 1
输入4,这是我到目前为止得到的:

    1
   21
  321
 4321
我想在数字之间加一个空格。这是我的代码:

import java.util.Scanner;
public class PatternTwo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int userInput;
        System.out.println("Please enter a number 1...9 : ");
        userInput = in.nextInt();
        String s="";
        int temp = userInput;
        for(int i=1; i<=userInput; i++ ) {

            for (int k= userInput; k>=i; k-- ) {
                System.out.printf(" ");
            }

            for(int j =i; j>=1; j-- ) {
                System.out.print(j);
            }


            System.out.println("");
        }

    }

}
import java.util.Scanner;
公共课模式二{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
int用户输入;
System.out.println(“请输入数字1…9:”);
userInput=in.nextInt();
字符串s=“”;
int temp=用户输入;
对于(int i=1;i=i;k--){
System.out.printf(“”);
}
对于(int j=i;j>=1;j--){
系统输出打印(j);
}
System.out.println(“”);
}
}
}

打印数字时,请在数字中间留出一个空格

// this works up n == 9
System.out.print(" " + j); 
对于n>9,问题是您需要在固定的空间量上打印数字和空格,但是数字包含的字符数会发生变化。一个解决方案是使用tab(如果您想要非常大的数字,可以使用多个)


在要打印的数字前面添加一个空格,并将上面的空格加倍,使其不是金字塔。大概是这样的:

import java.util.Scanner;
public class PatternTwo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int userInput;
        System.out.println("Please enter a number 1...9 : ");
        userInput = in.nextInt();
        String s="";
        int temp = userInput;
        for(int i=1; i<=userInput; i++ ) {

            for (int k= userInput; k>i; k-- ) { // <- corrected condition
                System.out.printf("  ");
            }

            for(int j = i; j>=1; j-- ) {
                System.out.print(j);

                // check if not 1 to avoid a trailing space
                if (j != 1) {
                    System.out.print(" ");
                }
            }


            System.out.println("");
        }

    }

}
import java.util.Scanner;
公共课模式二{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
int用户输入;
System.out.println(“请输入数字1…9:”);
userInput=in.nextInt();
字符串s=“”;
int temp=用户输入;
对于(inti=1;ii;k--){/=1;j--){
系统输出打印(j);
//如果不是1,请选中以避免出现尾随空格
如果(j!=1){
系统输出打印(“”);
}
}
System.out.println(“”);
}
}
}
编辑


多亏了我纠正了我的解决方案,删除了所有不必要或错误的空格

一个更干净的解决方案怎么样,它可以避免使用嵌套for循环:

public static void main(final String[] args) {
    final Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a number 1...9 : ");
    final int n = scanner.nextInt();

    final ArrayList<String> suffixes = new ArrayList<>();
    for (int i = 1; i <= n; i++) {
        suffixes.add(0, i + " ");

        final String prefix = String.join("", Collections.nCopies(n - i, "  "));
        final String suffix = String.join("", suffixes);

        System.out.println(prefix + suffix);
    }
}
publicstaticvoidmain(最终字符串[]args){
最终扫描仪=新扫描仪(System.in);
系统输出打印(“请输入数字1…9:”;
final int n=scanner.nextInt();
最终ArrayList后缀=新ArrayList();

对于(int i=1;i如果您对流感到满意:

public class PatternTwo {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int userInput;
    System.out.println("Please enter a number 1...9 : ");
    userInput = in.nextInt();
    String s = "";
    int temp = userInput;

    revRange(1, temp).forEach(n -> printNumbers(n, temp));
  }

  static IntStream revRange(int from, int to) {
    return IntStream.range(from, to)
      .map(i -> to - i + from - 1);
  }

  private static void printNumbers(int n, int max) {
    IntStream.rangeClosed(0, n -1)
      .forEach(num -> System.out.print("  "));
    revRange(1, max - n)
      .forEach(num -> System.out.print(num + " "));
    System.out.println();
  }
}

下面是对答案的修改,当
k
等于
i
时,通过修改k for循环退出条件,不会打印不必要的额外空白,同样,当
j
等于
i
时,也不会单独处理该情况

主要的总体变化是,在k-loop中,您需要打印2个空格,而不是1个空格,以实现所需的右侧对齐:

import java.util.Scanner;

class PatternTwo {

  private static void printPatternTwo(int n) {
    for (int i = 1; i <= n; i++) {
      for (int k = n; k > i; k--) {
        System.out.print("  ");
      }
      for (int j = i; j >= 1; j--) {
        System.out.print(j == i ? j : " " + j);
      }
      System.out.println();
    }
  }

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Please enter an integer between 1 and 9 inclusive: ");
    int userNum = -1;
    while (scanner.hasNext()) {
      if (scanner.hasNextInt()) {
        userNum = scanner.nextInt();
        if (userNum >= 1 && userNum <= 9) {
          scanner.close();
          break;
        } else {
          System.out.println("ERROR: Input number was not between 1 and 9");
          System.out.print("Enter a single digit number: ");
        }
      } else {
        System.out.println("ERROR: Invalid Input");
        System.out.print("Please enter an integer between 1 and 9 inclusive: ");
        scanner.next();
      }
    }

    printPatternTwo(userNum);
  }
}

另一种替代方法是使用
printf
并对每个数字使用
String.format

String.format("%1$" + length + "s", inputString) 
返回
inputString
如果
inputString.length
>=
length
则返回
inputString
,否则输入字符串将填充空格,使长度等于给定长度

例如:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int userInput;
    System.out.println("Please enter a number 1...9 : ");// you can use this also for numbers > 9
    userInput = in.nextInt();
    int digits = String.valueOf(userInput).length()+1;
    for(int i = 1; i<=userInput; i++){
        System.out.printf("%1$"+(digits*(userInput-i+1))+"s","");
        for(int k = userInput - (userInput-i); k >= 1; k--){
            System.out.print(String.format("%1$"+digits+"s", k));
        }
        System.out.println();
    }
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
int用户输入;
System.out.println(“请输入一个数字1…9:”;//您也可以将其用于大于9的数字
userInput=in.nextInt();
int digits=String.valueOf(userInput).length()+1;
对于(int i=1;i=1;k--){
System.out.print(String.format(“%1$”+数字+“s”,k));
}
System.out.println();
}
}

So,在System.out.print(j)后面添加一个空格@Stultuske会导致pyramid@XtremeBaumer然后他还需要为循环中的前导空格添加打印。这不会改变如果他想在这些值之间添加空格,他实际上应该在它们之间添加一个空格。欢迎来到stack overflow,只是想称赞你的代码。它看起来很好!继续编码注意事项:)@Stultuske我从来没有说过他不应该做什么,我只是说,你最初的提议是错误的,结果导致了一场失败pyramid@XtremeBaumer真的不应该。事实上,我测试了它,输出是你所期望的。我也得到了一个金字塔。。。您需要将上面的空格翻倍,因为与空格相比,数字的垂直大小翻了一倍。@XtremeBaumer更新了答案,应该也适用于更大的数字。虽然我不知道n>100时发生了什么,但我的屏幕不够大。我喜欢String.join建议。但在引擎盖下,它仍然是一个for循环;)没错,但这是关于可读性和可理解性,而不是性能优化。:)我改正了我的错误,谢谢你提出来
String.format("%1$" + length + "s", inputString) 
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int userInput;
    System.out.println("Please enter a number 1...9 : ");// you can use this also for numbers > 9
    userInput = in.nextInt();
    int digits = String.valueOf(userInput).length()+1;
    for(int i = 1; i<=userInput; i++){
        System.out.printf("%1$"+(digits*(userInput-i+1))+"s","");
        for(int k = userInput - (userInput-i); k >= 1; k--){
            System.out.print(String.format("%1$"+digits+"s", k));
        }
        System.out.println();
    }
}