【问题标题】:The code below should take in integers separated by spaces and print them to the screen, but it is not printing the first integer?下面的代码应该接受用空格分隔的整数并将它们打印到屏幕上,但它没有打印第一个整数?
【发布时间】:2018-02-12 02:46:41
【问题描述】:
import java.util.Scanner;

public class TestingCode {

  public static void main(String[] args)
  {


    int n; 
    int integers;


    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a single positive integer, n: ");
    n = scan.nextInt();

    System.out.println("Enter n integers separated by spaces: ");
    integers = scan.nextInt();

    for (int i=0; i < n; i++) {
        int input = scan.nextInt();
        System.out.println(input);
    }

    scan.close();
  }

}

输入

输入一个正整数,n:
5

输入 n 个用空格分隔的整数:
1 2 3 4 5

输出
2
3
4
5

预期输出
它应该打印出来
1
2
3
4
5

【问题讨论】:

  • 删除integers = scan.nextInt();
  • 比你 Elliott,解决了问题!

标签: java for-loop input printing integer


【解决方案1】:

第一个整数在for 循环之前已经用integers = scan.nextInt(); 读入。但它永远不会用System.out.println 打印出来。因此,只需删除我在下面注释掉的那一行:

Scanner scan = new Scanner(System.in);

System.out.println("Enter a single positive integer, n: ");
n = scan.nextInt();

System.out.println("Enter n integers separated by spaces: ");

// The below line read the first integer from input, but is never output with System.out.println().
// So just remove this line & reads in "n" number of integer in the "for" loop
// integers = scan.nextInt();

for (int i=0; i < n; i++) {
    int input = scan.nextInt();
    System.out.println(input);
}

scan.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2016-10-22
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多