【问题标题】:Java unexpected infinite loopJava 意外的无限循环
【发布时间】:2014-05-08 07:58:18
【问题描述】:

我的问题是我的方法进入了意外的无限循环,但我无法确定原因。该方法应该从用户那里获取输入并将其分配给三个不同的对象。然而,在循环运行两次并要求用户输入第三个对象的名称后,程序无限循环。我应该指出,我对 java 和学习编程还比较陌生。

这是代码(我已经用 !!!! 开始了 cmets,我认为这与问题有关):

private void readInput()    
//This method accepts input from the user about product data and sets the values of 
//product1, product2 and product3
//Also validates all input so as not to crash the program if the user enters incorrect data
{       
    String name;        
    int demandRate, productChoice=1; 
    final int MAXPRODUCTS=3;
    double setupCost, unitCost, inventoryCost, sellingPrice;

    Scanner console = new Scanner(System.in);

    while (productChoice <= MAXPRODUCTS)    
    //A loop that makes the user enter data for all three products and then stops after the third entry
    {                                      
        System.out.println("Please enter the product's name: ");
        name = console.next();       
        matesStore.isAProduct(name);     // checks whether the product name the user has entered is unique.
        while (matesStore.isAProduct(name))  
        //If a name that has already been entered is found, the user will be asked to reenter the name
        {
            System.out.println("That name is already in use. Please choose another: "); 
            name = console.next();
        }
        while (!matesStore.isAProduct(name))
        //If a name has not been used, the name is added to the product
        {
            matesStore.addProduct(name); //!!!!I suspect the problem is this line.
        }            
        System.out.println("Please enter the product's demand rate: ");
        demandRate = console.nextInt();                         
        System.out.println("Please enter the product's setup cost: ");
        setupCost = console.nextDouble();
        System.out.println("Please enter the product's unit cost: ");
        unitCost = console.nextDouble();
        System.out.println("Please enter the product's inventory cost: ");
        inventoryCost = console.nextDouble();
        System.out.println("Please enter the product's selling price: ");
        sellingPrice = console.nextDouble();
        matesStore.addData(productChoice, demandRate, setupCost, unitCost, inventoryCost, sellingPrice);    //Uses the method from the Store class to set the data values for the products.
        productChoice++;        
    }
    while (productChoice > MAXPRODUCTS)
    {
        System.out.println("The list is now full.");
        continueOption();
    }         
}//End of Method and Interface class

这是来自 Store 类的方法:

public boolean isAProduct(String product)
//Returns true if a name has been found otherwise returns false
{
    boolean found = false;
    int counter = 0;

    while (!found && (counter < MAXNUMBEROFPRODUCTS))
    {
        if (product.equalsIgnoreCase(product1.getName()))
        {
            found = true;
        }
        else if (product.equalsIgnoreCase(product2.getName()))
        {
            found = true;                 
        }
        else 
        {
            counter++;
        }            
    }        

    return found;
}//End of method

public void addProduct(String product)
//If isAProduct() returns false then the product name 
//entered by the user is stored in product1, product2 and product3 respectively

//!!!!I think this is where the problem originates but can't figure out why
{   
    if (numberOfProducts == 0) 
    //!!!!numberOfProducts has been declared as private int numberOfProducts=0;
    //I tried declaring numberOfProducts as a variable within addProduct()
    //but that just set the value to 0 each time and so only the name for product1 was set
    {
        product1.setName(product);
        numberOfProducts++;
    }
    else if (numberOfProducts == 1)
    {
        product2.setName(product);
        numberOfProducts++;
    }
    else if (numberOfProducts == 2)
    {                
        product3.setName(product);
    }            
    else
    {
        System.exit(0);
    }
} 

任何帮助或建议将不胜感激:)

干杯

【问题讨论】:

  • 第一个循环条件是 productChoice MAXPRODUCTS。是在 continueOption 中减少 productChoice 还是这是一个/问题?
  • 尝试插入一些调试语句,而不是试图猜测它在哪里循环。
  • 当您的程序进入无限循环时,究竟打印了什么?
  • 抱歉,我不明白为什么需要减少 productChoice。它从 1 开始,因此小于 3 并进入循环,然后在循环结束时增加 1,因此它变为 2 并再次进入循环,依此类推,直到值达到 4,在这种情况下循环结束并且通知用户列表已满,然后 continueOption() 将用户带回主界面。完成所有操作后,我是否应该将 productChoice 减回 0?对不起,我只是有点困惑:)
  • @Zeeshan 没什么,我输入第三个对象的名称,程序就停止接受输入。但它并没有停止,我必须手动停止程序,这就是为什么我认为它是一个无限循环。

标签: java infinite-loop


【解决方案1】:
while (!matesStore.isAProduct(name))
        //If a name has not been used, the name is added to the product
        {
            matesStore.addProduct(name); //!!!!I suspect the problem is this line.
        }       

第三个产品是无限循环的原因是因为你应该在这个语句中使用 If,while 也可以工作,但你看到有一个错误是由于你的方法 addProduct。如果您更改为 If it won't be an infinite loop 但是您的产品 3 将被窃听。

public boolean isAProduct(String product)
//Returns true if a name has been found otherwise returns false
{
    boolean found = false;
    int counter = 0;

    while (!found && (counter < MAXNUMBEROFPRODUCTS))
    {
        if (product.equalsIgnoreCase(product1.getName()))
        {
            found = true;
        }
        else if (product.equalsIgnoreCase(product2.getName()))
        {
            found = true;                 
        }
        else 
        {
            counter++;
        }            
    }        

    return found;
}//End of method

注意到您没有检查 product3,因此在搜索您的第 3 个产品名称时它总是返回 false。

!matesStore.isAProduct(name) = !false = true

维奥拉!!这就是while(true),一个无限循环!

通过在您的 isAProduct() 方法中实现 product3.getName() 来修复。

你的代码很乱,你应该为产品使用数组,你可以用数组更好地搜索。

public boolean isAProduct(String product)
//Returns true if a name has been found otherwise returns false
{
    boolean found = false;
    int counter = 0;

    while (!found && (counter < MAXNUMBEROFPRODUCTS))
    {
        if (product.equalsIgnoreCase(product1.getName()))
        {
            found = true;
        }
        else if (product.equalsIgnoreCase(product2.getName()))
        {
            found = true;                 
        }
        else if (product.equalsIgnoreCase(product3.getName()))
        {
            found = true;                 
        }
        else 
        {
            counter++;
        }            
    }        

    return found;
}//End of method      

【讨论】:

  • 非常感谢。我能够根据您的建议解决我的问题 :) 此外,该程序适用于一个特别要求我们不要使用数组的 uni 项目。我们才刚刚开始了解它们,我们的下一个任务需要我们修改这个程序以使用数组哈哈
  • @user3610513 我明白了,难怪你没有使用数组。数组将解决并使您的代码更具可读性。这很奇怪,因为我在学习方法之前学习了数组。我认为在方法和类之前先了解数据类型会更重要。然而,当我试图在我的大脑中调试你的代码时,阅读你的代码让我在工作场所感觉更加清醒!
  • 哈哈是的,这可能是有道理的,但我猜这取决于讲师。不过那很好!我觉得我只是在问这么简单且可能令人眼花缭乱的问题,哈哈:)
  • @MrPigeon 无论如何我注意到您不需要 matesStore.addProduct(name); while (!matesStore.isAProduct(name)){} 循环的 while 循环,因为之前您已经验证它应该是正确的,然后才允许用户突破循环。
  • 是的,我现在改了 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 2015-03-22
  • 1970-01-01
  • 2014-06-07
相关资源
最近更新 更多