简体   繁体   English

知道为什么不能将 `ichoice` 解析为变量吗?

[英]Any idea why `ichoice` can't be resolved to a variable?

I'm trying to write a do while loop to print out a menu until choice 5 is entered.我正在尝试编写一个 do while 循环来打印菜单,直到输入选项 5。

I have declared my variable ichoice as an integer and have not had any problems with it until my last line of code.我已经将我的变量ichoice声明为一个整数,并且在我的最后一行代码之前没有遇到任何问题。 Its taken me a while to get to this point so very confused as to why it wont work!我花了一段时间才达到这一点,所以很困惑为什么它不起作用!

import java.util.Scanner;

public class testCoinSorter {
    
    public static void main(String[] args) {
        //An example
        
        CoinSorter exampleOne = new CoinSorter("Pound Sterling (£)", 0, 10000, new int[] {10,20,50,100,200});
        
    
        //System.out.println(1);
        do {
            System.out.println("Choice 1 - Coin Calculator");
            System.out.println("Choice 2 - Multiple coin calculator");
            System.out.println("Choice 3 - Print coin list");
            System.out.println("Choice 4 -- display program configurations");
            System.out.println("Choice 5 - quit the program & save the data");
            Scanner in = new Scanner(System.in);
            int ichoice;
            ichoice = in.nextInt();
            switch(ichoice) {
                case 1:
                          // put code for enrolling a new student here
                          System.out.println("Enrolling a new student");
                          // etc etc
                    break;
                case 2:
                    // put code for entering a students mark here
                    System.out.println("Enter the students mark");
                    // etc etc
                    break;
                case 3:
                    // put code for printing out results here
                    System.out.println("Printing out results");
                    // Etc etc
                    break;
                case 4:
                    // put code for calculating final grade here
                    System.out.println("printing final grade");
                    // etc etc
                    break;
                default:
                    if(ichoice != 5) System.out.println("Unknown option");
                    // no need for a break
            } // End of the switch statement
        } while (ichoice != 5);
        
        
    }
}

Any clarification would be greatly appreciated任何澄清将不胜感激

ichoice variable is defined inside the do-while loop. ichoice变量在do-while循环中定义。 This makes the variable available only within the do-while loop block scope (which is defined by the { } braces).这使得该变量仅在do-while循环块范围内可用(由{ }大括号定义)。

To make it accessible in the while ( ) test expression you should move ichoice outside of the loop body eg before the do .要使其在while ( )测试表达式中可访问,您应该将ichoice移到循环体之外,例如在do之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM