如果用户回答 Y/y,我如何返回到 try 循环?我知道下面的代码不会询问用户的您想再试一次(是/否)吗?。我目前只能使用 bufferedReader 。
import java.io.*;
public class Num10 {
public static void main(String[] args){
String in="";
int start=0, end=0, step=0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.print("Input START value = ");
in=input.readLine();
start=Integer.parseInt(in);
System.out.print("Input END value = ");
in=input.readLine();
end=Integer.parseInt(in);
System.out.print("Input STEP value = ");
in=input.readLine();
step=Integer.parseInt(in);
}catch(IOException e){
System.out.println("Error!");
}
if(start>=end){
System.out.println("The starting number should be lesser than the ending number");
System.exit(0);
}else
if(step<=0){
System.out.println("The step number should always be greater than zero.");
System.exit(0);
}
for(start=start;start<=end;start=start+step){
System.out.println(start);
}
System.out.println("\nDo you want to try again (Y/N)?");
}
}
最佳答案
do ... while
循环适合于此。
boolean again = false;
do
{
// your code here
again = askQuestion();
} while(again);
或者您可以只使用常规的 while
循环:
boolean again = true;
while(again)
{
// your code here
again = askQuestion();
}
对于这两种方法,askQuestion
是另一种向用户询问问题并返回 true
或 false
的方法。
关于java - 询问是/否以返回循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6964880/