I have the code below, my question is : is it possible to make a method run continuously until I input a special character
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;
}
I'm quite new to java and this only my first question here, hope is not too silly
It sounds to me like you need to think about your structure differently. The remainder
method probably shouldn't interact with the console - you need to loop in the code calling it:
// 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"));
Then your remainder
method should just compute the remainder and return it.
See more on this question at Stackoverflow