如何在循环中分别记录每个输入?

我的问题是只有第五个输入被打印,而其余的则没有


Scanner ns = new Scanner(System.in);


int n = 0;


int i=1;  

while(i<=5)

{  

    System.out.println("enter a number");  

    n = ns.nextInt();

    i++;  

}  


System.out.println(+n);

System.out.println(+n);

System.out.println(+n);

System.out.println(+n);

System.out.println(+n);

假设我分别输入了 1, 2, 3, 4, 5,它应该看起来像这样



1

2

3

4

5

但相反我得到


5

5

5

5

5


慕娘9325324
浏览 104回答 3
3回答

凤凰求蛊

您可以将输入参数存储到ArrayListpublic static void main(String[] args) {&nbsp; &nbsp; Scanner ns = new Scanner(System.in);&nbsp; &nbsp; int n = 0;&nbsp; &nbsp; int i = 1;&nbsp; &nbsp; List<Integer> params = new ArrayList<>();&nbsp; &nbsp; while (i <= 5) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("enter a number");&nbsp; &nbsp; &nbsp; &nbsp; n = ns.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; params.add(n);&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; }&nbsp; &nbsp; for (Integer param : params) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(param);&nbsp; &nbsp; }}输出:1enter a number2enter a number3enter a number4enter a number512345

蛊毒传说

请循环打印数字。请参阅下面的代码:&nbsp; &nbsp;Scanner ns = new Scanner(System.in);&nbsp; &nbsp; int n = 0;&nbsp; &nbsp; int i=1;&nbsp;&nbsp;&nbsp; &nbsp; while(i<=5)&nbsp; &nbsp; {&nbsp;&nbsp;&nbsp; &nbsp; System.out.println("enter a number");&nbsp;&nbsp;&nbsp; &nbsp; n = ns.nextInt();&nbsp; &nbsp; System.out.println(n);&nbsp; &nbsp; i++;&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp;&nbsp;

RISEBY

所有输入都被打印,问题是 while 循环将 n 设置为值 5,然后打印 5 五次。您正在寻找的正确代码是:int n = 0;int i=1;&nbsp;&nbsp;while(i<=5){&nbsp;&nbsp;&nbsp; System.out.println("enter a number");&nbsp;&nbsp;&nbsp; n = ns.nextInt();&nbsp; i++;&nbsp;&nbsp;&nbsp; System.out.println(+n);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java