So basically my code works (or at least I'm pretty sure it does). I removed the last if/else statements and it all runs. However when I put it in I get a "max" may not have been initialized.
Could someone please explain to me how to initialize it. I know the basics behind it. Apparently it's not giving the values to "max" which is preventing the program from compiling.
Here is the code:
import java.util.Scanner; /** * MaxOfThree is a program that asks the user to input 3 different * integers, separated by a space and all on one line. * * It then checks if all 3 are different. If not, it informs user * about the error and terminates the program. * Otherwise, it proceeds with computing the maximum of these 3 * integers and prints it. * * */ import java.util.Scanner; public class MaxOfThree { public static void main(String[] args) { // INITIALIZE YOUR SCANNER FOR GETTING INPUT FROM THE KEYBOARD Scanner keyboard = new Scanner(System.in); // ASK THE USER TO TYPE IN THREE DIFFERENT INTEGERS. System.out.print("Enter three different integers, all on one line."); int max; // Maximum of i, j, and k. // Declare and read i, j, k. int i; int j; int k; i = keyboard.nextInt(); // ADD CODE HERE for reading j and k. // --> j = keyboard.nextInt(); k = keyboard.nextInt(); // Validate input by checking if any two are equal. // If yes, inform user of the error and // terminate by executing System.exit(0). // ADD CODE after if. HERE YOU MAY USE LOGICAL AND (&&) or OR (||). // --> if ((i==j) || (i==k) || (k==j)) { System.out.println("Equal integers are not allowed! Exiting..."); System.exit(0); } else { System.out.println("You gave me legal numbers"); } // Since input is valid, proceed with determination of maximum. // Important: DO NOT USE LOGICAL AND (&&) or OR (||) IN THIS PART. // Just write nested else .. if ... else if .. statement. // This is just one long if - else - if - else.... statement. // For example, if (i > j) // if ( i > k ) max = i; // Complete the if-else statement // ADD CODE AFTER else. // --> if (i > j) { if (i > k) { max = i; } else { max = k; } } if (j > i) { if (j > k) { max = j; } else { max = k; } } if (k > j) { if (k > i) { max = k; } else { max = i; } } // Print max as shown in the sample session. // ADD CODE HERE. // --> System.out.println("Maximum of Three integers " + i + ", " + j + ", " + k + " is " + max); } }
Oh and I cannot use && and ||. I have to compare them with < > =, and if else statements.