The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
March 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

"faking" decisions with the substring() method

Posted by jmm342 on March 08, 2001 at 4:30 PM

I'm reading an introductory JAVA book that says you can fake a decision using the substring() method. It uses the following problem to illustrate the use of the technique:

The user inputs: (1) The # of gallons of gas in the tank. (2) The fuel efficiency in miles per gallon. (3) The distance the user wants to travel. The program will then print out either "You will make it" or "You will not make it".

You have to declare a variable x that is equal to the maximum number of miles the user is capable of driving minus the desired distance that the user inputs. Then you want to set a variable n=1 if x >= 0 or n=0 if x < 0. Then you can solve the problem as follows:

String answer = " not ";
System.out.println("You will" + answer.substring(0, 5 - 4 * n)
+ "make it");

Here is the general algorithm to determine n:

x + Math.abs(x) = 2x if x >= 0
x + Math.abs(x) = 0 if x < 0

Then you simply divide (x + Math.abs(x)) by 2x, except the trick here is that you have to worry about the case when x = 0. This is what I cannot figure out. I've tried using exponential and trigonometric functions and I still can't find a formula that satisfies all three cases: x > 0, x = 0, and x < 0.

Does anyone have any ideas on how to solve this. I've looked at it for three hours and still can't figure it out. Thanks !




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us