#java #loops #variables
#java #циклы #переменные
Вопрос:
Я пытаюсь написать цикл do while, чтобы распечатать меню, пока не будет введен вариант 5.
Я объявил свою переменную ichoice
как целое число, и у меня не было никаких проблем с этим до моей последней строки кода. Мне потребовалось некоторое время, чтобы добраться до этого момента, так что я очень смущен тем, почему это не сработает!
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 amp; 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);
}
}
Любые разъяснения будут с благодарностью
Комментарии:
1. Переместите
int ichoice;
раньшеdo {
.
Ответ №1:
ichoice
переменная определяется внутри do-while
цикла. Это делает переменную доступной только в пределах do-while
области действия блока цикла (которая определяется {
}
фигурными скобками).
Чтобы сделать его доступным в while ( )
тестовом выражении, вы должны выйти ichoice
за пределы тела цикла, например, перед do
.