Question
In java, fix this code so it does not accept negative values for m and n * Program should not accept -1 -1, 1 -1
In java, fix this code so it does not accept negative values for m and n
* Program should not accept -1 -1, 1 -1 , -1 1
import java.util.Scanner;
import java.util.StringTokenizer;
public class AckerApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean run = true;
while (run) {
Scanner inputReader = new Scanner(System.in);
int m = 0,n = 0;
// Prompt for input
// quit program with q
System.out.println("Input Two integers separated by a space character (enter \"q\" to quit)");
String i = inputReader.nextLine();
// Get m and n
if (i.equalsIgnoreCase("q")) {
System.out.println("program terminated");
System.exit(0);
}
else {
// takes in integer values of m and n
try {
StringTokenizer sb=new StringTokenizer(i);
m = Integer.valueOf( sb.nextToken());
n = Integer.valueOf( sb.nextToken());
AckerFunction ak = new AckerFunction();
int result = ak.acker(m, n);
System.out.println("Total Number of invocations = " + ak.countOfInvocations() + " result = " + result);
// catch exception for invalid input ( not integer)
} catch (Exception e) {
System.out.println("Invalid input");
}
}
}
}
}
public class AckerFunction {
private int spaces = 0;
private int numberOfInvocations = 0;
// getter for data field "numberOfInvocations"
public int countOfInvocations() {
return numberOfInvocations;
}
public int acker(int m, int n) {
++numberOfInvocations;
++spaces;
printSpaces();
System.out.print("Enter Method Acker: m = " + m + " n = " + n + " ");
int result = 0;
if(m == 0)
result = n+=1;
else if(n == 0) {
result = acker(m-1, 1);
} else {
result = acker(m-1, acker(m,n-1));
}
printSpaces();
System.out.print("Leave Method Acker: m = " + m + " n = " + n + " ");
this.spaces -= 1;
return result;
}
private void printSpaces() {
for(int i = 0; i < spaces; i++)
System.out.print(" ");
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started