【问题标题】:How to limit the user from typing in more than three integers into the console?如何限制用户在控制台中输入超过三个整数?
【发布时间】:2016-05-26 19:01:27
【问题描述】:

我希望用户只能在控制台中输入不超过三个数字。有什么方法可以限制或阻止控制台接受键盘输入?

谢谢

import java.util.Scanner;
public class Numbers { 
public static void main(String[] args) {
 Scanner userInput = new Scanner(System.in);
  System.out.print("Type three integers ");
  int firstInt = userInput.nextInt();
  int secondInt = userInput.nextInt();
  int thirdInt = userInput.nextInt();
  System.out.println(firstInt + secondInt + thirdInt);
  }
}

【问题讨论】:

  • 请注意,stackoverflow 不是代码编写服务。在寻求帮助之前,请向我们展示您的尝试。
  • 好吧,我不知道。对不起。我只是想了解。
  • 也许至少显示一些您尝试过的代码?
  • 我更新了代码,我知道这很简单,但是我们都必须从正确的地方开始。

标签: java input keyboard


【解决方案1】:
 int count = 3;
        Scanner z = new Scanner(System.in);
        List<Integer> l = new ArrayList<>();
        while(count>0)
        {
           int n = z.nextInt();
           l.add(n);
           count--;

        }
        Runtime.getRuntime().exit(0); 

Runtime.getRuntime().exit(0) 将允许代码跳过代码中的下一行。

试试看

希望这是您正在寻找的解决方案

【讨论】:

  • 为什么要让程序在读取三个值后立即退出程序?据推测,输入它们是有原因的,比如可能要对它们进行一些计算。
  • 我更新了代码。这很简单,我是新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2011-04-02
  • 1970-01-01
  • 2011-05-09
相关资源
最近更新 更多