输入字符串后,为什么我的代码不会进入while循环?

时间:2017-10-26 21:45:55

标签: java methods

我必须在我的代码中执行一些方法,然后将它们全部转到main方法。一切都正常工作,但当我输入一个字符串到“getOrder”方法时,它不会检查字符串是否为真,然后完成剩下的代码。有人可以帮帮我吗?我尝试做一个if和else语句,但它们也没有用。谢谢

import java.util.Random;
import java.util.Scanner;

public class App {

public static void main(String[] args) {
    //Get banner message
    welcomeUser();

    //Get product array
    String[] products = getProducts();

    //Get prouct order from user aka the LA
    getOrder(products);

    //Does the product exist?
    if(getOrder(products) == true) //yup it exists
    {
        //Get the *price*
        getPrice();
        double fPrice = getPrice();

        //Get the TAX
        getTax(fPrice);
        double tax = getTax(fPrice);

       //Get the total sale
        getTotal(fPrice, tax);

        //output the total sale
        double transaction =  getTotal(fPrice, tax);
        printTotal(transaction);

    }
    else
        System.out.print("Not found");


}

public static void welcomeUser()
{
    System.out.println("Hello! Welcome to the Fruit Market!");
}

public static String[] getProducts()
{
    String [] productList = new String [5];
    productList[0] = "Banana";
    productList[1] = "Pineapple";
    productList[2] = "Grapes";
    productList[3] = "Strawberries";
    productList[4] = "Kiwi";
    //System.out.println(Arrays.toString(productList));
    return productList;
}

public static boolean getOrder(String[] stuff)
{
    Scanner scan = new Scanner(System.in);
    String usersFruitChoice;
    System.out.println("Please enter a fruit you would like to buy.");
    usersFruitChoice = scan.nextLine();

    boolean valid = false; 

    while(!valid)
    {
        for (String stuff1 : stuff) {
            valid = stuff1.equalsIgnoreCase(usersFruitChoice);
        }        
   }

     return valid;

}


}

}

2 个答案:

答案 0 :(得分:1)

罪魁祸首似乎是你的for循环:

for (String stuff1 : stuff) {
        valid = stuff1.equalsIgnoreCase(usersFruitChoice);
    }       

如果数组中的后续值与valid中的任何值不匹配,则代码的此部分将遍历整个产品数组并覆盖usersFruitChoice的值。尝试为Kiwi输入usersFruitChoice,看看代码是否进入while循环以验证是否发生了此错误。

如果找到与break匹配的有效条目,则可以使用usersFruitChoice语句解决此问题,因为它会提前退出循环并且不会始终导致检查数组中的最后一个值反对usersFruitChoice

for (String stuff1 : stuff) {
        if (stuff1.equalsIgnoreCase(usersFruitChoice)) {
             valid = true;
             break;
        };
    }  

答案 1 :(得分:0)

考虑删除这一行 - 它什么都不做:

//Get prouct order from user aka the LA
    getOrder(products);