Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java的while循环问题_Java - Fatal编程技术网

java的while循环问题

java的while循环问题,java,Java,我有两个循环,我似乎不能正常工作。基本上,如果我写错了东西,它会把我送到一个我必须正确书写的地方。当我到达那个点时,无论我输入什么,我都不能离开输入。任何一行写着“无效”的话都不能给出我需要的结果。请帮帮我!这是代码 import java.util.Arrays; import java.util.Scanner; public class EZRealEstateSimulator { public static void main(String[] args) { /*

我有两个循环,我似乎不能正常工作。基本上,如果我写错了东西,它会把我送到一个我必须正确书写的地方。当我到达那个点时,无论我输入什么,我都不能离开输入。任何一行写着“无效”的话都不能给出我需要的结果。请帮帮我!这是代码

import java.util.Arrays;
import java.util.Scanner;

public class EZRealEstateSimulator {

    public static void main(String[] args) {
    /* Declarations */
        String buy = "Buy";
        String rent = "Rent";
        String sell = "Sell";
        String quit = "Quit";       
    String [] availableHomes;
        availableHomes = new String [6];
        availableHomes [0] = "516 Dunkin St, Ontario, CA";
        availableHomes [1] = "224 Mooclid Ave, Ontario, CA";
        availableHomes [2] = "342 Pine Ave, Chino Hills, CA";
        availableHomes [3] = "1488 Overprice Ave, Chino Hills, CA";
        availableHomes [4] = "632 Clayton Drive, Chino Hills, CA";
        availableHomes [5] = "778 Lakeside Ct, Rancho Cucamonga, CA";
    String [] availableApartments;
        availableApartments = new String [6];
        availableApartments [0] = "1248 Helm St, APT: 678, Rancho Cucamonga,CA";
        availableApartments [1] = "892 Low Park Ave, APT:32, Rancho Cucamonga,CA";
        availableApartments [2] = "120 Maven Ct, APT: 55, Ontario,CA";
        availableApartments [3] = "423 Scimitar St, APT: 12, Ontario,CA";
        availableApartments [4] = "918 Mystic Parkway, APT:3, Rancho Cucamonga,CA";
        availableApartments [5] = "1316 Cobalt Ct, APT: 27, Chino Hills,CA";
        String [] activeCities;
        activeCities = new String [3];
        activeCities [0] = "Ontario";
        activeCities [1] = "Rancho Cucamonga";
        activeCities [2] = "Chino Hills";
    String house = "House";
    String apartment = "Apartment";
    int [] paymentPlan;
        paymentPlan = new int [4];
        paymentPlan [0] = 250;
        paymentPlan [1] = 500;
        paymentPlan [2] = 750;
        paymentPlan [3] = 1000;
        int downPayment = 200;
    String completeReport;
    int changeLoop;
        int changeAltLoop;
    String customerAddress = " ";
    String customerCellNumber = " ";
    String customerHomeNumber = " ";
        String customerName = " ";
        String housingTenure;
        String livingArea;
        String cities;
        String purchasedHome = " ";
        String purchasedApartment = " ";
        int errorLoop;
        int gameLoop;


        Scanner input = new Scanner (System.in);

    /* Personal Info Prompts */


        System.out.println("Would you like to buy, or quit program? Type Buy or Quit "); 
        housingTenure = input.nextLine ();

        System.out.println("Would this be for an apartment or home? Type House or Apartment");
        livingArea = input.nextLine ();

        System.out.println("Please enter your full name: ");
        String name = input.nextLine ();
        customerName = name;

        System.out.println("Please enter your full address: ");
        String address = input.nextLine ();
        customerAddress = address;

        System.out.println("Please enter your home number: ");
        String hNumber = input.nextLine ();
        customerHomeNumber = hNumber;

        System.out.println("Please enter your cell number: ");
        String cNumber = input.nextLine ();
        customerCellNumber = cNumber;

gameLoop = 0;
while (gameLoop == 0) {

                /* Buy */

                changeLoop = 0;
                while (changeLoop == 0 && livingArea.equals(house)) {                
                    System.out.println("Which city would you like to buy property in? Type Ontario, Chino Hills, or Rancho Cucamonga ");
                    cities = input.nextLine ();
                if (!cities.equals(activeCities [0]) || !cities.equals(activeCities [1]) || !cities.equals(activeCities [2])) {
                    System.out.println("Invalid. Please enter either Ontario, Chino Hills, or Rancho Cucamonga");
                    cities = input.nextLine ();
                } else {
                        continue;
                    }

                    if (cities.equals(activeCities [0])) {
                        System.out.println("The available homes are: " + availableHomes [0] +  " and "   + availableHomes [1] + " .Please select one by typing availableHomes [#] ");
                        purchasedHome = input.nextLine ();
                        if (!purchasedHome.equals(availableHomes[0]) || !purchasedHome.equals(availableHomes [1])) {
                            System.out.println("Invalid");
                            purchasedHome = input.nextLine ();
                        } else { 
                            changeLoop += 1;
                        }                       
                    } else if (cities.equals(activeCities [1])) {
                        System.out.println("The available homes are: " + availableHomes [5] +  " .Please select one by typing availableHomes [#] ");
                        purchasedHome = input.nextLine ();
                        if (!purchasedHome.equals(availableHomes[5])) {
                            System.out.println("Invalid");
                            purchasedHome = input.nextLine ();
                        } else { 
                            changeLoop += 1;
                        }   

                    } else {
                        System.out.println("The available homes are: " + availableHomes [2] +  " , "  + availableHomes [3] +  " and "  + availableHomes [4] +  " .Please select one by typing availableHomes [#] ");
                        purchasedHome = input.nextLine ();
                        if (!purchasedHome.equals(availableHomes[2]) || !purchasedHome.equals(availableHomes [3]) || !purchasedHome.equals(availableHomes [4])) {
                            System.out.println("Invalid");
                            purchasedHome = input.nextLine ();
                        } else { 
                            changeLoop += 1;
                        }   
                    }
                }

                changeAltLoop = 0;
                while (changeAltLoop == 0 && livingArea.equals(apartment)) {   
                    System.out.println("Which city would you like to buy property in? Type Ontario, Chino Hills, or Rancho Cucamonga ");
                    cities = input.nextLine ();
                    if (!cities.equals(activeCities [0]) || !cities.equals(activeCities [1]) || !cities.equals(activeCities [2])) {
                    System.out.println("Invalid. Please enter either Ontario, Chino Hills, or Rancho Cucamonga");
                    cities = input.nextLine ();
                    }
                    if (cities.equals(activeCities [0])) {                  
                    System.out.println("The available apartments are: " + availableApartments [2] + " and " + availableApartments [3]);
                    purchasedApartment = input.nextLine ();
                        if (!purchasedApartment.equals(availableApartments[2]) || !purchasedApartment.equals(availableApartments [3])) {
                            System.out.println("Invalid");
                            purchasedApartment = input.nextLine ();                  
                    } else if (cities.equals(activeCities [1])) {
                    System.out.println("The available apartments are: " + availableApartments [0] + " , " + availableApartments [1] + " and " + availableApartments [4]);
                    purchasedApartment = input.nextLine ();
                       if (!purchasedApartment.equals(availableApartments [0]) || !purchasedApartment.equals(availableApartments [1])) {
                            System.out.println("Invalid");
                            purchasedApartment = input.nextLine ();
                       }
                       } else {
                    System.out.println("The available apartments are: " + availableApartments [5]);
                    purchasedApartment = input.nextLine ();
                        if (!purchasedApartment.equals(availableApartments [5])) { 
                            System.out.println("Invalid");
                            purchasedApartment = input.nextLine ();
                        } else { 
                            changeAltLoop += 1;
                        }
                    }
                }
                }


                    /* eof */

                    System.out.println("Please select a monthly payment plan price: " + paymentPlan [0] + " , " + paymentPlan [1] + " , " + paymentPlan [2] + " and " + paymentPlan [3]);
                    System.out.println("REMAINDER! Each payment is due on the 5th of each month and a $200 down payment is required.");
                    int payment = input.nextInt ();

                    System.out.println("Processing data into detailed report...");
                    System.out.println("                                       ");
                    System.out.println("                                       ");
                    System.out.println("                                       ");

                    System.out.println("---Complete Report---");
                    System.out.println("Customer Name: " + name);
                    System.out.println("Customer Address: " + address);
                    System.out.println("Customer Home Number: " + hNumber);
                    System.out.println("Customer Cell Number: " + cNumber);
                    System.out.println("Customer Payment Plan: " + payment);
                    System.out.println("Customer Purchased House: " + purchasedHome);
                    System.out.println("Customer Purchased Apartment: " + purchasedApartment);



                }   

                }       
                }
这是很多代码:) 无论如何,您所述的问题是由于您的if条件造成的

if (!cities.equals(activeCities[0]) || !cities.equals(activeCities[1]) || !cities.equals(activeCities[2])) {
    System.out.println("Invalid. Please enter either Ontario, Chino Hills, or Rancho Cucamonga");
    cities = input.nextLine();
} else {
    continue;
}
因为您使用的是OR(| |)操作,所以它会遍历所有条件,直到找到一个true。所以为了跳过这个循环,所有表达式都应该返回false,这意味着输入的城市应该等于所有活动城市,这是不可能的。所以它会一直显示无效。因此,首先将逻辑更改为

if (!cities.equals(activeCities[0]) && !cities.equals(activeCities[1]) && !cities.equals(activeCities[2])) {
    System.out.println("Invalid. Please enter either Ontario, Chino Hills, or Rancho Cucamonga");
    cities = input.nextLine();
}
还要注意else条件。您应该删除整个else,因为此处的continue语句会重新启动while循环,并且只要您输入有效的city,它就会反复询问相同的问题

快速提示

  • 使用
    equalsIgnoreCase
    进行比较会更好,用户可以这样做 键入“house”而不是“house”
  • 使用集合API,如列表、映射等,而不是数组。这会 将上述ifs与
    如果(!activeCities.contains(cities))
    。代码将简洁明了 清洁工
完整示例

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class EZRealEstateSimulator {

    private static final Set<String> activeCities, propertyOptions, commands;
    private static final Map<String, Set<String>> availableHomes, availableApartments;
    private static final String[] prompts = new String[9];
    private static final int[] paymentPlan = { 250, 500, 750, 1000 };
    private static final int downPayment = 200;

    private static String userOption, customerAddress, customerCellNumber, customerHomeNumber, customerName, propertyType, city, purchasedHome, purchasedApartment, customerPaymentPlan;
    private static int i = 0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        do {
            System.out.println(getPrompt(i));
            String value = input.nextLine();
            if(!isValidOption(value, i)){
                System.out.println("Invalid Option!!");
                continue;
            }
            i++;
        } while(i < 9);
        input.close();

        System.out.println("Processing data into detailed report...");
        System.out.println("                                       ");
        System.out.println("                                       ");
        System.out.println("                                       ");
        System.out.println("---Complete Report---");
        System.out.println("Customer Name: " + customerName);
        System.out.println("Customer Address: " + customerAddress);
        System.out.println("Customer Home Number: " + customerHomeNumber);
        System.out.println("Customer Cell Number: " + customerCellNumber);
        System.out.println("Customer Payment Plan: " + customerPaymentPlan);
        System.out.println("Customer Purchased House: " + purchasedHome);
        System.out.println("Customer Purchased Apartment: " + purchasedApartment);
    }

    private static String getPrompt(int index) {
        String message = prompts[index];

        switch (index) {
            case 6: //City Question
                message = String.format(message, activeCities.toString());
                break;

            case 7: //Available house/apartment question
                String opts = ("House".equalsIgnoreCase(propertyType) ? join(availableHomes.get(city)) : join(availableApartments.get(city)));
                message = String.format(message, propertyType, opts);
                break;

            case 8: //Payment Question
                message = String.format(message, Arrays.toString(paymentPlan), downPayment);
                break;

            default:
                break;
        }

        return message;
    }

    private static boolean isValidOption(String value, int index) {
        boolean isValid = true;

        switch (index) {
            case 0:
                userOption = value;
                isValid = commands.contains(value.toUpperCase());
                if(isValid && "Quit".equalsIgnoreCase(userOption)){
                    i = 10; // Breaks out of main while loop.
                }
                break;
            case 1:
                propertyType = value;
                isValid = propertyOptions.contains(value.toUpperCase());
                break;
            case 2:
                customerName = value;
                break;
            case 3:
                customerAddress = value;
                break;
            case 4:
                customerHomeNumber = value;
                break;
            case 5:
                customerCellNumber = value;
                break;
            case 6:
                city = value;
                isValid = activeCities.contains(value);
                break;
            case 7:
                if ("House".equalsIgnoreCase(propertyType)) {
                    purchasedHome = value;
                    isValid = availableHomes.get(city).contains(value);
                } else {
                    purchasedApartment = value;
                    isValid = availableApartments.get(city).contains(value);
                }
                break;
            case 8:
                customerPaymentPlan = value;
                try {
                    if (Arrays.binarySearch(paymentPlan, Integer.parseInt(value)) == -1) {
                        isValid = false;
                    }
                } catch (NumberFormatException e) {
                    isValid = false;
                }
                break;

            default:
                break;
        }

        return isValid;
    }

    public static String join(Set<String> array) {
    final int noOfItems = array.size();
    final StringBuilder buf = new StringBuilder(noOfItems * 16);
    int idx = 0;
    for (String value : array) {
        if (idx > 0) {
        buf.append("\n");
        }
        idx++;
        buf.append(idx + ". " + value);
    }
    return buf.toString();
    }

    // Initialize constants
    static {
        availableHomes = new TreeMap<String, Set<String>>(String.CASE_INSENSITIVE_ORDER);
        availableHomes.put("Ontario", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("516 Dunkin St, Ontario, CA"); add("224 Mooclid Ave, Ontario, CA"); }});
        availableHomes.put("Chino Hills", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("342 Pine Ave, Chino Hills, CA"); add("1488 Overprice Ave, Chino Hills, CA"); add("632 Clayton Drive, Chino Hills, CA"); }});
        availableHomes.put("Rancho Cucamonga", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("778 Lakeside Ct, Rancho Cucamonga, CA"); }});

        availableApartments = new TreeMap<String, Set<String>>(String.CASE_INSENSITIVE_ORDER);
        availableApartments.put("Rancho Cucamonga", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("1248 Helm St, APT: 678, Rancho Cucamonga,CA"); add("892 Low Park Ave, APT:32, Rancho Cucamonga,CA"); add("918 Mystic Parkway, APT:3, Rancho Cucamonga,CA"); }});
        availableApartments.put("Ontario", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("120 Maven Ct, APT: 55, Ontario,CA"); add("423 Scimitar St, APT: 12, Ontario,CA"); }});
        availableApartments.put("Chino Hills", new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{ add("1316 Cobalt Ct, APT: 27, Chino Hills,CA"); }});

        activeCities = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        activeCities.addAll(Arrays.asList(new String[] {"Ontario", "Rancho Cucamonga", "Chino Hills"}));

        propertyOptions = new HashSet<String>(Arrays.asList(new String[] { "HOUSE", "APARTMENT" }));
        commands = new HashSet<String>(Arrays.asList(new String[] { "BUY", "QUIT" }));

        prompts[0] = "Would you like to buy, or quit program? Type Buy or Quit";
        prompts[1] = "Would this be for an apartment or home? Type House or Apartment";
        prompts[2] = "Please enter your full name: ";
        prompts[3] = "Please enter your full address: ";
        prompts[4] = "Please enter your home number: ";
        prompts[5] = "Please enter your cell number: ";
        prompts[6] = "Which city would you like to buy property in? Options %s :";
        prompts[7] = "The available %s are:\n%s\nPlease select one by typing availableHomes [#] ";
        prompts[8] = "Please select a monthly payment plan price: %s \n REMAINDER! Each payment is due on the 5th of each month and a $%s down payment is required.";
    }
}
导入java.util.array;
导入java.util.HashSet;
导入java.util.Map;
导入java.util.Scanner;
导入java.util.Set;
导入java.util.TreeMap;
导入java.util.TreeSet;
公共类房地产刺激器{
私有静态最终集活动城市、属性选项、命令;
私有静态最终地图可用家庭、可用部门;
私有静态最终字符串[]提示=新字符串[9];
私有静态final int[]paymentPlan={2505007501000};
私人静态最终整数首付=200;
私有静态字符串userOption、customerAddress、customerCellNumber、customerHomeNumber、customerName、propertyType、city、purchasedHome、PurchasedPartment、customerPaymentPlan;
私有静态int i=0;
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
做{
System.out.println(getPrompt(i));
字符串值=input.nextLine();
如果(!isValidOption(值,i)){
System.out.println(“无效选项!!”);
继续;
}
i++;
}而(i<9);
input.close();
System.out.println(“将数据处理成详细报告…”);
System.out.println(“”);
System.out.println(“”);
System.out.println(“”);
System.out.println(“---完成报告---”;
System.out.println(“客户名称:+客户名称”);
System.out.println(“客户地址:“+customerAddress”);
System.out.println(“客户家庭号码:“+客户家庭号码”);
System.out.println(“客户单元号:“+customerCellNumber”);
System.out.println(“客户付款计划:“+客户付款计划”);
System.out.println(“客户购买的房屋:“+purchasedHome”);
System.out.println(“客户购买的公寓:“+购买的公寓”);
}
私有静态字符串getPrompt(int索引){
字符串消息=提示[索引];
开关(索引){
案例6://城市问题
message=String.format(message,activeCities.toString());
打破
案例7://可用房屋/公寓问题
String opts=(“House.equalsIgnoreCase(propertyType)?join(availableHomes.get(city)):join(AvailablePartments.get(city));
message=String.format(message,propertyType,opts);
打破
案例8://付款问题
message=String.format(message,Arrays.toString(paymentPlan),首付);
打破
违约:
打破
}
返回消息;
}
私有静态布尔值isValidOption(字符串值,整数索引){
布尔值isValid=true;
开关(索引){
案例0:
userOption=值;
isValid=commands.contains(value.toUpperCase());
if(isValid&“Quit”.equalsIgnoreCase(userOption)){
i=10;//中断主while循环。
}
打破
案例1:
propertyType=值;
isValid=propertyOptions.contains(value.toUpperCase());
打破
案例2:
客户名称=价值;
打破
案例3:
customerAddress=值;
打破
案例4:
customerHomeNumber=值;
打破
案例5:
customerCellNumber=值;
打破
案例6:
城市=价值;
isValid=activeCities.contains(值);
打破
案例7:
如果(“房屋”。相等信号案例(属性类型)){
purchasedHome=价值;
isValid=availableHomes.get(city).contains(value);
}否则{
PurchasedPartment=价值;
isValid=availablepartments.get(城市).contains(值);
}
打破
案例8:
customerPaymentPlan=价值;
试一试{
if(Arrays.binarySearch(paymentPlan,Integer.parseInt(value))=-1){
isValid=false;
}
}捕获(数字格式){
isValid=false;
}
打破