java按q退出程序,循环的前哨问题,以允许进入Java中的退出程序

I'm having trouble at the bottom part where i am trying to set the sentinel exit key to quit..

im not sure exactly how i am supposed to do it.

int number;

do

{

Scanner Input = new Scanner(System.in);

System.out.print("Enter a positive integer or q to quit program:");

number = Input.nextInt();

}

while(number >= 0);

do

{

Scanner Input = new Scanner(System.in);

System.out.print("Input should be positve:");

number = Input.nextInt();

}

while(number < 0);

do

{

Scanner quit = new Scanner(System.in);

System.out.print("Enter a positive integer or quit to end program");

input = quit.nextstring();

}

while (!input.equals(quit))//sentinel value allows user to end program

{

quit = reader.next()

解决方案

A couple tips:

Don't initialize a new Scanner every iteration, that will be really

expensive.

Notice that as you wrote it, if a user enters a negative

number, they can't get back "up" into the first while loop to keep

entering positive numbers.

I assume you want this all in one while

loop, not three, or these actions would have to be performed in

sequence to break through all 3 sentinel conditions.

System.out.print() will not add a new line, which will look awkward.

Working on these assumptions, here's a version that has one sentinel variable endLoop that gets reset if the quit condition is met, i.e. the user enters 'quit'. If they enter a negative number, the "Input should be positive" message will print, then the loop will start over, and if they enter a positive number then nothing will happen (I marked where to add whatever action goes there) and the loop will start over. We only cast the input (which is a String) to an int after checking that it isn't 'quit', because if we try to cast a String (like 'quit') to an int, the program will crash.

Scanner input = new Scanner(System.in);

boolean endLoop = false;

String line;

while (!endLoop) {

System.out.print("Enter a positive integer or 'quit' to quit program: ");

line = input.nextLine();

if (line.equals("quit")) {

endloop = true;

} else if (Integer.parseInt(line) < 0) {

System.out.println("Input should be positive.");

} else {

int number = Integer.parseInt(line);

//do something with the number

}

}

Edited to use 'quit' instead of 0 for termination condition.

Note that this program will crash if the user enters anything other than a number or 'quit'.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值