Java通过使用数组方法通过忽略其他数字来打印最后一个数字

时间:2018-11-09 22:03:00

标签: java

我试图让我的代码打印输出但使用数组方法的数字。

package pkg11;

import java.util.Scanner;

public class Main {

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

    System.out.println("How many number do you want to put?");
    int b = in.nextInt();

    for (int z = 1; z <= b; z++) {
      System.out.println("Input your" + " " + z + " " + "number");
      x = in.nextInt();
    }

    System.out.println();
    int[] a = new int[x];;

    for (int i = 0; i < a.length; i++) {
      System.out.println(a[i]);
    }
  }
}

问题是,当打印时,它只打印最后一个值,例如,我想输入3个数字,第一个是1,第二个是2,第三个是3,它打印第三个而没有第一个2。

1 个答案:

答案 0 :(得分:3)

仔细查看您的以下代码片段,并尝试找出错误:

for (int z = 1; z <= b ; z++) {
    System.out.println("Input your" +" " +z +" " +"number");
    x = in.nextInt();
}

// here you create the array
int [] a = new int [x];

如果没有发现它:在从控制台读取所有值之后,创建要保存每个整数的数组。您无法将用户输入存储在数组中,因为当时尚不知道。

然后,您实际上做了什么?

您一直x使用相同的变量x = in.nextInt();,覆盖了每个输入。

我该如何解决该问题?

Scanner in = new Scanner(System.in);
int x = 0;

System.out.println("How many number do you want to put?");
int b = in.nextInt();

int[] a = new int[b];

for (int z = 0; z < b; z++) {
    System.out.println("Input your" + " " + (z + 1) + " " + "number");
    a[z] = in.nextInt();
}

for (int i = 0; i < a.length; i++) {
    System.out.println(a[i]);
}

首先,在读取值之前声明int[] a = new int[b];,并为每个输入分配a[z] = in.nextInt();数组。另外,我对循环索引进行了一些修改,使事情变得更容易。

好,我还能做什么?

除了用户输入非数字外,此代码还更防弹!如果您要查找更多内容,可以使用in.nextLine()Integer.valueOf()来防止用户输入字符串而不是数字。

Scanner in = new Scanner(System.in);

int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");

amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
    System.out.println("Please enter a number greater than one:");
    amountOfNumers = in.nextInt();
}

int[] numbers = new int[amountOfNumers];

for (int i = 0; i < amountOfNumers; i++) {
    System.out.println("Input your " + (i + 1) + " number: ");
    numbers[i] = in.nextInt();
}

System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);