【发布时间】:2017-04-30 10:44:59
【问题描述】:
在我的项目中,我有一个模拟选择菜单的循环,当用户选择一个数字时,我想进入下一个循环,但这是循环内 switch 语句的一部分。 我的代码是:
while(entrychoice!=8){
String alphabet= "abcdefghijklmnopqrstuvwxyz"; //tyxaio onoma
String onoma = "";
Random random = new Random();
int randomLen = 1+random.nextInt(9);
for(int p = 0; p < randomLen; p++) {
char c = alphabet.charAt(random.nextInt(26));
onoma+=c;
}
//Random rand=new Random();//this.kratisid=kratisid; kai stin main bazo random
//int kratisid=rand.nextInt(500)+100;//Παραγει τυχαιο κωδικο κρατησης μεταξυ 100 και 500
int kratisid = getRandomInt(); //dimiourgia monadikou kai tyxaiou kratisid
Random rand1=new Random();
int afixi=rand1.nextInt(30)+1;//tyxaia mera afixis se ena mina
Random rand2=new Random();
int mdiam=rand2.nextInt(30)+1;//tyxaies meres diamonis se ena domatio
Random rand3=new Random();
int atoma=rand3.nextInt(4)+1;
Domatio d=null;//reference to the domatio pou egine kratisi
reservation r=new reservation(onoma,kratisid,afixi,mdiam,atoma,d);
//r.antistoixisidtodom(d,dom);
Hotel1.addkratisianyroom(r);//prosthiki tyxaias kratisis r se tyxaio domatio
//25% pithanotita gia tyxaia akyrosi kratisis
Random randprob=new Random();
int prob=randprob.nextInt(4)+1;//prob is the probability of cancelling a random kratisi
if (prob==1)//25%
{ //epilogi tyxaias kratisis apo tin lista kratiseon Rlist gia akyrosi
Random randomGeneratorList=new Random();
int index=randomGeneratorList.nextInt(Rlist.size())+0;//+0;
int kratisiFRCID=Hotel1.Rlist.get(index).kratisid;//kratisiFRCid means kratisiForRandomCancel ID
Hotel1.cancelkratisi(kratisiFRCID);//Rlist.get(index).cancel....
}
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\",\"3\",\"4\",\"5\",\"6\",\"7\"or\"8\"");
if(scanchoice.hasNextInt()){
entrychoice = scanchoice.nextInt();
}
switch(entrychoice)
{
case 1:
continue;
break;**
}
}
请注意,代码继续但很大,其他选项无关紧要。正如您在 switch 语句的 case1 中看到的,如果用户输入 1 以进入下一个循环,但编译器说 break;将永远不会执行,这会破坏我的 switch 语句。请建议如何使用 switch 语句和用户输入进入下一个循环,就像我在这里所做的那样。提前谢谢。
【问题讨论】:
-
如果您还有其他问题,请将其作为一个单独的问题提出,并带有自己的标题、答案、投票、cmets 等。这里没人会看到它。
-
@davidxxx 我不知道您希望我如何回复已删除的帖子,但它的第一句话是不正确的。
continue可以在循环内的任何地方使用,包括switch语句。 -
@EJP 对不起。我彻底删除了。确实你是对的。
标签: java loops while-loop switch-statement