W5 Homework Assignment Solution

Assignment

1.    Write a program that asks a user to enter three integers and either:

·         displays the message “No solution” if it is not possible to add two of the numbers entered to get the third.  For example, if the user enters 1, 2, and 4, the program should display “No solution”, since  1+2 ≠ 4, 1+4 ≠ 2, and 4+2 ≠ 1.

·         Otherwise, the program displays “__ +__ = __”. For example, if the user enters 1, 4, and 3, the program should display: “1 + 3 = 4”.

·         Hint: this solution requires an approach using if, else if, and else.


2) Write a 2nd version of this program that uses iteration (a while-loop) to keep asking the user for a different set of values as long as no solution is found.

Solution
/**
 * HW5 solution
 * 10/9/2009
 * mlh
 */
import java.util.Scanner;
/**
 * @author hornick
 * This program prompts the user for 3 values, and determines if any 2 of the values sum to the 3rd. 
 */
public class SolutionFinder {

	/**
	 * @param args - not used
	 */
	public static void main(String[] args) {

		boolean solutionFound = false;
		while( !solutionFound ) { // as long as we have no solution, keep repeating 

			System.out.print("Enter 3 integers, separated by space (Ex: 1 2 3): " );
			Scanner kbdReader = new Scanner( System.in );

			// read the input and convert to int values
			int x = kbdReader.nextInt();
			int y = kbdReader.nextInt();
			int z = kbdReader.nextInt();

			// There are 3 possible combinations that work: x+y=z, x+z=y, or y+z=x
			if( (x+y)==z ) { // check if x+y=z is the solution
				System.out.printf("Solution found %3d + %3d = %3d", x, y, z );
				solutionFound = true; // indicate we found a solution
				
			} else if( (x+z)==y ) {  // check if x+z=y is the solution
				System.out.printf("Solution found %3d + %3d = %3d", x, z, y );
				solutionFound = true;
				
			} else if( (y+z)==x ) { // check if y+z=x is the solution
				System.out.printf("Solution found %3d + %3d = %3d", y, z, x );
				solutionFound = true;
				
			} else { // no solution possible
				System.out.println("No solution found; try again");
			}
		} // end while
	}
}