【问题标题】:Calling a scanner the number of times the user inputted in java调用扫描仪用户在java中输入的次数
【发布时间】:2016-10-01 17:43:06
【问题描述】:

这是我的第一个 java 项目之一,我正在尝试制作一个迷你计算器,现在我正在做加法。

我想要它做的是它会询问用户他们想要添加多少个数字,然后在你输入所有数字之后,Java 代码必须获取所有输入的数字。

下面是目前还不能用的附加部分:

    private static void Addition() { //I already added the Scanner plugin
        System.out.println("How many numbers would you like to add?");

        Scanner adds = new Scanner(System.in);
        int addsput = adds.nextInt();

        Scanner numa = new Scanner(System.in);

        for(int addloop=1; addloop>addsput; addloop++) {

            int numaput = adds.nextInt();
            //somehow I want to get all the numbers

        }

    //Here I want to add all the numbers they typed
    }   

所以我希望你明白这一点。任何帮助都会很棒,因为我一直在寻找大约一个小时来弄清楚这一点。谢谢。

【问题讨论】:

  • “不起作用”是什么意思?它有什么作用?你期望它做什么?仅仅说“我希望你明白”是不够的。请提供更多细节
  • 为什么你有两台扫描仪?
  • 好的,我会解释它应该做什么:P lol
  • 第一个扫描器是看他们想要多少个数字,第二个是扫描用户输入的数字。

标签: java for-loop java.util.scanner


【解决方案1】:

您有两种选择,要么将值读入数组,要么在读取值时求和。

您只需要一个Scanner 对象,而您的for 循环存在一些问题:

private static void addition() {
    Scanner input = new Scanner(System.in);

    System.out.println("How many numbers would you like to add?");
    int amountNumbers = input.nextInt();

    int sum = 0;
    for (int counter = 0; counter < amountNumbers; counter++) {
        sum += input.nextInt();
    }

    System.out.println("Sum: " + sum);
}

使用数组:

private static void addition() {
    Scanner input = new Scanner(System.in);

    System.out.println("How many numbers would you like to add?");
    int[] numbers = new int[input.nextInt()];

    for (int index = 0; index < numbers.length; index++) {
        numbers[index] = input.nextInt();
    }

    int sum = 0;
    for (int index = 0; index < numbers.length; index++) {
        sum += numbers[index];
    }

    System.out.println("Sum: " + sum);
}

这是使用 Java 8 中的IntStream 的更高级方法:

private static void addition() {
    Scanner input = new Scanner(System.in);

    System.out.println("How many numbers would you like to add?");
    int amountNumbers = input.nextInt();

    int sum = IntStream.generate(input::nextInt)
                       .limit(amountNumbers)
                       .sum();

    System.out.println("Sum: " + sum);
}

【讨论】:

  • 谢谢!这有很大帮助。我可能很快就会了解数组,因为直到现在我才真正需要它们。
  • @MattGotJava 我进行了编辑以展示如何使用数组进行操作,以及更高级的方法(我会这样做)。
【解决方案2】:

我建议更改以下几点: 您只需要一台扫描仪。至于加和,如果你在循环之前创建变量,你可以在你输入的同一行中加和。

你还把 符号混在一起了。您希望循环继续进行,直到变量 addloop 增加了用户想要输入要添加的数字的次数。因此,循环应该继续,直到达到用户输入的数字,而不是相反。

   System.out.println("How many numbers would you like to add?");

    Scanner adds = new Scanner(System.in);
    int addsput = adds.nextInt();

    int sum = 0;

    for(int i = 0; i < addsput; i++){
        sum += adds.nextInt();
    }

    System.out.println(sum);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多