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

时间:2019-11-20 16:30:56

标签: java loops

我希望获得以下输出:

$ 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;
            }
        }
    }
}

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

编辑:我尝试简化代码

1 个答案:

答案 0 :(得分: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");
            }
        }
    }
}