首页 > 解决方案 > 为什么我不能在 While 循环内返回?

问题描述

我正在我的程序中研究一个必须返回值 purchaseMethod 的方法。while 循环需要一直运行到控制台输入“Q”为止。我遇到的问题是我无法在 while 循环中返回。有没有办法解决?可能制作一个数组或for循环?如果 return 语句必须在 while 循环之外,我将如何将值保持为 purchaseAmount 的总计值。

public static int getShoppingList(){
    Scanner input = new Scanner(System.in);
    int eight = 8;
    int hat = 32;
    int patch = 2;
    int sword = 20;
    int map = 100;
    int shirt = 150;
    int quanEight = 0;
    int quanHat = 0;
    int quanPatch = 0;
    int quanSword = 0;
    int quanMap = 0;
    int quanShirt = 0;
    int count = 0;

    System.out.println("Enter Item Code, ? or Q: ");
    String code = input.next();
    // Convert input into character
    char ch = code.charAt(0);
    // Convert string into uppercase
    ch = Character.toUpperCase(ch);
    // Calculate total 

    while (count != 0){
        int purchaseAmount = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
        if (ch == '?'){
            System.out.println("Valid Item codes are: 8 I H M S T.");
            System.out.println("Q to quit.");
        }
        else if (ch == '8'){
            quanEight ++; 

        }
        else if (ch == 'I'){
            quanHat++;
        }
        else if (ch == 'H'){
            quanPatch++;
        }    
        else if (ch == 'M'){
            quanMap++;
        }
        else if (ch == 'S'){
            quanSword++;
        }
        else if (ch == 'T'){
            quanShirt++;
        }     
        else if (ch == 'Q'){
            count++;
            System.out.println("Pirate Trading Post");
            System.out.println(quanEight + " Genuine Piece Of Eight\n " + quanHat + " Pirate Hat\n " + quanPatch + 
                " Eye Patch\n " + quanSword + " Sword\n " + quanMap + " Treasure Map\n " + quanShirt + " T-Shirt\n ");
            System.out.println("Total: " + purchaseAmount + " bits");
            return purchaseAmount;
        }
    }

}

标签: javawhile-loop

解决方案


问题是一个编译问题:

        int count = 0;

        while (count != 0){    // count **IS** 0, does not enter
            // your stuff
        }

        // no return

推荐阅读