【问题标题】:Cant print the value of scan.nextIn(); [closed]无法打印 scan.nextInt() 的值; [关闭]
【发布时间】:2019-01-17 00:32:56
【问题描述】:

我正在尝试从数组中删除用户整数输入。但是,我无法获得输入的值。

while(keepGoing)
    {
        while (!scan.hasNextInt() ) 
        {        
            scan.next(); 
            System.out.print('\n'+"Choose a valid number: "); 
        }
        int unitA = scan.nextInt();
        if (unitA < 1) 
        {
            System.out.print('\n'+"Choose one of the options: ");
            keepGoing = true;
        }
        else if (unitA > 14) 
        {
            System.out.print('\n'+"Choose one of the options: ");
            keepGoing = true;
        }
        else
            lengthValue.remove(unitA);
        scan.close();
        keepGoing = false;
    }
    //lengthValue.remove(int unitA);
    System.out.println(unitA);

【问题讨论】:

  • 好吧,hasNextInt()next() 寻找完全不同的令牌。为什么要以这种方式测试流?
  • 我只是想避免输入字符串。我知道这是一种奇怪的方式,你有什么更好的方法吗?
  • 我为您重新缩进了您的代码,使其与大括号匹配。仔细看看。

标签: java arrays if-statement while-loop java.util.scanner


【解决方案1】:

在我看来,您输入输入后忘记按“Enter”。只要您按下“Enter”键,扫描仪就可以读取输入。您的解决方案对我来说似乎是正确的。我能够在我的 PC 上正常运行它。

您可以在这里找到类似的问题: How to use Scanner to accept only valid int as input

【讨论】:

  • System.out.println(unitA); 无法定义 unitA
  • 由于 unitA 是在您的 while 循环内定义的,因此您无法在循环外访问它,因此它超出了范围。您需要做的是在“while”语句之前定义 unitA。并在循环内分配其值。
猜你喜欢
  • 2012-04-08
  • 2021-04-08
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多