【问题标题】:Can't get my scanner nextLine() to work properly within a while loop [duplicate]无法让我的扫描仪 nextLine() 在 while 循环内正常工作 [重复]
【发布时间】:2021-01-19 08:48:57
【问题描述】:

我目前正在尝试创建一个循环循环,用户输入值以添加到链接列表中。但是每次输入值中有一个空格时,它都会导致循环跳过标志 nextLine() 输入。

代码如下:

while(true)
        {
            
            System.out.println("Please enter product name: ");
            productName = input.nextLine();

            
            System.out.println("Please enter the Price: ");
            price = input.nextDouble();
        
            productList.addProduct(productName, price);
        
            System.out.println("Are you done with this transaction? Y/N: ");
            stopFlag = input.nextLine();
            
            if(stopFlag.equalsIgnoreCase("y"))
                break;
        }

如果我输入“villainous”作为第一个字符串,然后输入 22.99 作为双精度值,它可以正常工作。然后我可以输入 y/n 退出。但!如果我说输入“Villainous exp”作为第一个字符串,第二个双输入工作正常,然后最后一个跳过,我得到如下输出:

请输入产品名称:

邪恶的经验

请输入价格:

22.99

您完成了这笔交易吗?是/否:

请输入产品名称:

我不知道如何让它不跳过底部输入或理解它为什么会这样做。

【问题讨论】:

    标签: java input while-loop java.util.scanner


    【解决方案1】:
    import java.util.*;
    
    public class Main
    {
    
    
    
      public static void main (String[]args)
      {
        Scanner input = new Scanner (System.in);
        boolean flag=false; int no=1; 
        for (int i=0;i<no && flag==false;i++)
          {
    
        System.out.println ("Please enter product name: ");
        String productName = input.nextLine ();
        System.out.println ("Please enter the Price: ");
        Double price = input.nextDouble ();
    
        // productList.addProduct(productName, price);
    
          System.out.println ("Are you done with this transaction? Y/N: ");
        char c = input.next (".").charAt (0);
    
        if (c == 'y')
          {
            System.out.println ("OK ");
                System.out.println ("Entry Saved! ");
                flag=true; 
          }
        else {
            no++;
        }
            input.nextLine(); 
    
          }
      }}
    

    编辑:程序现在应该可以运行了。 java.util.Scanner 类的 nextLine() 方法将此扫描器前进到当前行并返回被跳过的输入。此函数打印当前行的其余部分,在末尾省略行分隔符。下一个设置在行分隔符之后。由于此方法继续搜索输入以寻找行分隔符,因此如果不存在行分隔符,它可能会搜索所有输入以查找要跳过的行。

    阅读更多关于它的信息 https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多