Assignment
· 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 } }