Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle Database 10g Insider Solutions

Authors: Arun R. Kumar, John Kanagaraj, Richard Stroupe

1st Edition

0672327910, 978-0672327919

More Books

Students also viewed these Databases questions

Question

How does franchising differ from other forms of business ownership?

Answered: 1 week ago