仅当程序收到特殊输入时,如何才能停止其输入循环?

问题描述 投票:-1回答:1

我希望获得此输出:

$ java Rp6  
zipcode: 4328024  
4328024: 浜松市立西小学校

zipcode: 9691622  
not found

zipcode: -1  
bye  
$

程序应继续接受邮政编码,直到输入的值小于0。

对于我制作的程序,它在第一个邮政编码之后停止。

import java.util.Scanner;

class Rp6 {
    static String[] zipcodes = new String[] { "100", "200", "300" };

    public static void main(String[] args) {
        int i = 0;
        System.out.print("Zipcode: ");
        Scanner scan = new Scanner(System.in);
        int zipcodez = scan.nextInt();
        for (String zip : zipcodes) { // loop through zipcodes
            i++;
            if (zipcodez == Integer.parseInt(zip)) {
                System.out.println("found");
                break;
            } else if (i == 3 && zipcodez != Integer.parseInt(zip)) {
                System.out.println("not found");
            } else if (zipcodez <= 0) {
                System.out.println("bye");
                break;
            }
        }
    }
}

我正在考虑使用循环,但不确定将循环放在何处。你们有什么建议吗?

编辑:我试图简化代码

java loops
1个回答
0
投票

该代码当前仅遍历邮政编码:for (String zip : zipcodes)

如果您有加载邮政编码列表的代码,则应首先遍历该文件以加载列表。然后,一旦加载,在scan上进行第二个循环,该循环将反复获得标准输入。

类似这样的东西:

import java.util.Scanner;

class Rp6 {
    static String[] zipcodes = new String[] { "100", "200", "300" };

    public static void main(String[] args) {
        // Start an input loop to check the loaded zipcodes
        Scanner scan = new Scanner(System.in);
        int zipcodez = 0;
        while (zipcodez >= 0) {
            System.out.print("Zipcode: ");
            zipcodez = scan.nextInt();
            // stop the loop if the user enters -1
            if (zipcodez < 0) {
                System.out.println("bye");
                break;
            }

            // check if the user's zipcode is in zipcodes
            boolean found = false;
            for (String zipcode : zipcodes) {
                if (zipcodez == Integer.parseInt(zipcode)) {
                    System.out.println(zipcode);
                    found = true;
                }
            }
            if (!found) {
                System.out.println("not found");
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.