我有下面的代码,我的问题是:是否可以让一个方法连续运行直到我输入一个特殊字符
public static int remainder (int dividend, int divisor){
while ( dividend >= divisor ){
dividend -= divisor;
}
System.out.println("Result: "+ dividend);
System.out.println("Continue? Y/N"); // if Y, go back and run with different input value, otherwise return the result
return dividend;
}
我是 java 的新手,这只是我的第一个问题,希望不要太傻
最佳答案
在我看来,您需要以不同的方式考虑您的结构。 remainder
方法可能不应该与控制台交互 - 您需要在代码中循环调用它:
// Calling code, e.g. main
Console console = System.console();
if (console == null) {
System.out.println("Unable to get console. Aborting.");
System.exit(1); // Or continue somehow without this...
}
String response;
do {
console.printf("Enter a dividend: ");
int dividend = Integer.parseInt(console.readLine());
console.printf("Enter a divisor: ");
int divisor = Integer.parseInt(console.readLine());
int result = remainder(dividend, divisor);
console.printf("Result: %d%n", result);
console.printf("Continue? (Y/N) ");
response = console.readLine();
} while (response.equals("Y"));
那么您的remainder
方法应该只是计算余数并返回它。
关于java - 是否可以使方法连续运行直到我输入特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22588491/