有人知道如何同时递增和递减并将输出并排放置吗?

pcww981p  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(389)

编写一个应用程序,要求用户输入一个数字。然后,您的程序将根据您输入的数字显示一个开始和结束的数字,并在右侧显示与您在左侧显示的数字相反的数字。
预期产量:

  1. Enter a number: 5
  2. 1 5
  3. 2 4
  4. 3 3
  5. 4 2
  6. 5 1

我试着制作一个带有递增和递减数字的空心框,并将其他代码作为注解来尝试生成预期的输出。但我还是做不到。

  1. import java.util.Scanner;
  2. public class MyClass {
  3. public static void main(String args[])
  4. {
  5. System.out.print("Enter a number: ");
  6. Scanner input = new Scanner (System.in);
  7. int num = input.nextInt();
  8. System.out.print("\n");
  9. for (int i = 0; i < num; ++i) {
  10. for (int j = 0; j < num; ++j) {
  11. if (i == 0) {
  12. System.out.print((j + 1) + " ");
  13. //} else if (i == num-1) {
  14. System.out.print((num - j) + " ");
  15. } else if (j == 0) {
  16. System.out.print((i + 1) + " ");
  17. //} else if (j == num-1) {
  18. System.out.print((num - i) + " ");
  19. //} else {
  20. System.out.print(" ");
  21. }
  22. }
  23. System.out.println();
  24. }
  25. }
  26. }
g9icjywg

g9icjywg1#

因为这是家庭作业,所以我会给出指导而不是代码。
左边的列看起来很容易生成—一个简单的循环就可以了。
考虑左右数字之间的关系。注意,它们的总数总是6,或者更一般地说 n + 1 . 右边的这列可以通过减去 in + 1 ,在哪里 i 是左列值。

pzfprimi

pzfprimi2#

你想得太多了(;->)。没那么复杂。
有一种可能的方法:

  1. public class MyClass {
  2. public static void main(String args[])
  3. {
  4. System.out.print("Enter a number: ");
  5. Scanner input = new Scanner (System.in);
  6. int num = input.nextInt();
  7. System.out.print("\n");
  8. int i = 1;
  9. int j = num;
  10. while (i >= num) {
  11. System.out.println(i + " " + j);
  12. i++;
  13. j--;
  14. }
  15. }

还有一个:

  1. public class MyClass {
  2. public static void main(String args[])
  3. {
  4. System.out.print("Enter a number: ");
  5. Scanner input = new Scanner (System.in);
  6. int num = input.nextInt();
  7. System.out.print("\n");
  8. for (int i = 1; i <= num; ++i) {
  9. System.out.println(i + " " + (num - i + 1));
  10. }
  11. }
展开查看全部

相关问题