Results 1 to 13 of 13
  1. #1
    MSteinman is offline Member
    Join Date
    Mar 2009
    Posts
    6
    Rep Power
    0

    Default Sorting 3 Integers Using If Else

    Im having a little trouble trying to sort 3 integers using if-else statements. An example would help alot. Here is what I've got currently. Thanks

    import javax.swing.JOptionPane;
    public class MDS03_01 {

    //Program for 3 Integers to sort

    public static void main(String[] args) {
    String firstInput; //first input entered by user
    String secondInput; //second input entered by user
    String thirdInput; //third input entered by user

    //program reads information (numbers) entered by the user.
    firstInput = JOptionPane.showInputDialog("Enter your first number");
    secondInput = JOptionPane.showInputDialog("Enter your second number");
    thirdInput = JOptionPane.showInputDialog("Enter your third number");

    //converting the input to a integer from the string answer.
    int a = Integer.parseInt(firstInput);
    int b = Integer.parseInt(secondInput);
    int c = Integer.parseInt(thirdInput);

    Also, my second program has to read a number of integers read in from input from the user and then sum and average the integers. How would you do that? Thanks

  2. #2
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    What do you mean by sorting your integers? Is there any particular way they need to be sorted? Also, when posting code, please place the code inside code tags. Selecting the code and clicking the # button works as well
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  3. #3
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Another question... does this need to be done in a JOptionPane? I don't know whether it would work, but using a console seems like it would work better.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  4. #4
    MSteinman is offline Member
    Join Date
    Mar 2009
    Posts
    6
    Rep Power
    0

    Default

    I have to sort them Lowest, Middle, Highest. I have to use JOptionPane, which kind of stinks. If it weren't for rules I would probably use an Array which is much easier IMO. Thanks

  5. #5
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Hmm... I cant help you then. I have no experience using JOptionPane. My if/else statements wouldn't compile anyway when I tried to make an example for you... I'll keep trying and post it for you, but you'll have to convert it to JOptionPane.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  6. #6
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default

    FYI... because apparently you can't use arrays, you can place your ints in an array and then sort using arrays.sort ():
    Java: Sorting Arrays
    Arrays (Java Platform SE 6)

    For doing the second program, use a loop to gather the users entry and with each loop add up each user's entry and keep track of the number of times the program loops with a counter (for example counter++).

    Luck,
    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  7. #7
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    heres my code, it compiles perfectly now though I'm not sure how much it will help. If you don't want your program to throw exceptions everywhere, you're going to need a lot of try/catch statements. My application loops, but since it's a console, I don't know what you'll have to do to it. It may not work at all with JObjectPane, but I would guess that you wont have to do too much. You will have to change System.out.print statements and the way the strings are set, and you will also need different imports The while loops are optional, they simply loop until the user wants to exit or valid strings are entered.

    Java Code:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    
    import java.lang.Integer;
    import java.lang.NumberFormatException;
    
    public class IntegerReader {
    	//may or may not be necessary
    	static BufferedReader reader;
    	static String input1, input2, input3, InputChecker, 
    		          ApplicationRestart,AnswerLoop;
    	static int num1, num2, num3,sum, average, Highest, Middle, Lowest;
    	
    	public static void main(String[]args) throws IOException{
    		
    		reader = new BufferedReader(new InputStreamReader(System.in));
    		
    		ApplicationRestart = "yes";
    		
    		while("yes".equals(ApplicationRestart)||"Yes".equals(ApplicationRestart)){
    		System.out.print("What is your first number?\n");
    		input1 = reader.readLine();
    		
    		//loops until the first number resolves as a whole number
    		while(num1 == 0){
    		try{
    			num1 = Integer.parseInt(input1);
    		}
    		catch(NumberFormatException input1E){		
    			System.err.print("That is not an integer.  " +
    					"Please enter an integer.  Decimals are not allowed.\n");
    			input1 = reader.readLine();	
    		}
    		}
    
    		System.out.print("Your first number is: "+ num1 + 
    				"  \nWhat is your second number?\n");
    		input2 = reader.readLine();
    		
    		//loops until the second number resolves as a whole number
    		while(num2 == 0){
    			try{
    				num2 = Integer.parseInt(input2);
    			}
    			catch(NumberFormatException input1E){		
    				System.err.print("That is not an integer.  " +
    						"Please enter an integer.  Decimals are not allowed.\n");
    				input2 = reader.readLine();	
    			}
    			}
    		System.out.print("Your second number is: "+ num2 + 
    				"  \nWhat is your third number?\n");
    		input3 = reader.readLine();
    		
    		//loops until the third number resolves as a whole number
    		while(num3 == 0){
    			try{
    				num3 = Integer.parseInt(input3);
    			}
    			catch(NumberFormatException input1E){		
    				System.err.print("That is not a whole number.  " +
    						"Please enter a whole number.  Decimals are not allowed.\n");
    				input3 = reader.readLine();	
    			}
    			}
    		System.out.print("Your third number is: "+ num3);
    		System.out.print("\n\nYour numbers are: "+num1+", "+num2+", and "+num3+"\n\nIs this correct?\n");
    		InputChecker = reader.readLine();
    		//add all integers together here
    		sum = num1 + num2 + num3;
    		/** if using a different number of integers, edit
    			the 3 below to match the number of integers
    		*/
    		average = sum/3;
    		
    		
    		AnswerLoop = "yes";
    		
    	/**The below statements confirm that the numbers
    	 * are correct, and if they are not, the program
    	 * asks for the correct numbers.
    	 * The below statements also determine what number
    	 * Highest, Middle, and Lowest, by checking if num1
    	 * or num2 fit the criteria, and if they do not fit
    	 * the criteria, num3 is set as the correct number.
    	 * The program then displays the average and the sum
    	 * of the numbers, as well as the Highest, Middle,
    	 * and Lowest numbers.
    	*/
    	while("yes".equals(AnswerLoop)){
    		if ("yes".equals(InputChecker) || ("Yes".equals(InputChecker))){
    			System.out.print("\nThe sum of your numbers is: "+sum + "\nThe average of your numbers is: "+average);
    			if(num1 > num2 && num1 > num3){
    				Highest = num1;}
    			else
    			if(num2 > num1 && num2 > num3){
    				Highest = num2;}
    			else {Highest = num3;};
    			System.out.println("\nYour highest number is: "+ Highest);
    			
    			if(num1 < num2 && num1 > num3 || num1 > num2 && num1 < num3){
    				Middle = num1;}
    			else
    			if(num2 < num1 && num2 > num3 || num2 > num1 && num2 < num3){
    				Middle = num2;}
    			else{Middle = num3;};
    			System.out.println("Your middle number is: "+ Middle);
    			
    			if(num1 < num2 && num1 < num3){
    				Lowest = num1;}
    			else
    			if(num2 < num3 && num2 < num3){
    				Lowest = num2;}
    			else {Lowest = num3;};
    			System.out.println("Your lowest number is: "+ Lowest);
    			num1 = 0;
    			num2 = 0;
    			num3 = 0;
    			System.out.print("\nDo you wish to restart the application?\n");
    			ApplicationRestart = reader.readLine();
    			AnswerLoop = "no";
    		} else
    		if ("no".equals(InputChecker) || ("No".equals(InputChecker))) {
    			num1 = 0;
    			num2 = 0;
    			num3 = 0;
    			System.out.print("Please enter your numbers again.\n\n");
    			AnswerLoop = "no";}
    
    		else {System.out.print("Invalid answer, please enter yes or no.\n");
    		InputChecker = reader.readLine();};
    		}
    		}
    		System.out.print("\n\n\n\n\n\n\n\n\n\n\n\nThe application has closed.\n\n\n\n");
    	}
    }
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  8. #8
    MSteinman is offline Member
    Join Date
    Mar 2009
    Posts
    6
    Rep Power
    0

    Default

    Thanks for the code. I did edit it a little, using only the IF/Else statements. I guess I forgot to use the && inbetween the expressions, so that was the real kicker in this program. Thanks for the help.
    Now how could I get the user to input an unspecified # of integers (Not determined by me)? I would guess just a standard loop until the user decides to exit. Thanks for the help again!!

  9. #9
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    yes it is... one error that definitely needs to be fixed

    on line 129 while setting Lowest, the if statement for num2 only compares it to num3. The if/else statements for Lowest should be these:
    Java Code:
    if(num1 < num2 && num1 < num3){
    				Lowest = num1;}
    			else
    			if(num2 < num1 && num2 < num3){
    				Lowest = num2;}
    			else {Lowest = num3;};
    the code also has numerous problems that are hard to find, but shouldn't be too hard to fix...
    I wont fix the code posted here, but I will tell you what is wrong with it. All these errors can be fixed with a little creativeness.
    1. (Original Post)If 0 is entered as an integer, the program will loop infinitely.
    2. (Original Post)If num1 and num2 are the same, Highest, Lowest, and Middle will show up as num3.(if the error mentioned at the beginning of this post is fixed)

    There may be more hard to find errors. I will edit this post with date and time of edit as I find them(assuming I find any). Any major problems will include the code edit required to fix it.

    Also, a standard loop would work for entering a number of integers unspecified by you, but without using arrays and numerous other things, you could not determine the highest, middle, and lowest numbers.
    Last edited by Singing Boyo; 03-23-2009 at 04:02 AM.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  10. #10
    MSteinman is offline Member
    Join Date
    Mar 2009
    Posts
    6
    Rep Power
    0

    Default

    Now I just need a loop that goes on until the user specifies to quit and then add up the integers and average them out.

  11. #11
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    ok, so what you can do is this:

    1: use a while loop such as this:
    Java Code:
    while("yes".equals(LoopString)){(the code you want to loop goes here}
    or
    Java Code:
    while("no".equals(QuitString)){(the code you want to loop goes here}
    at the end of the loop, ask if the user wants to enter another number, and LoopString/QuitString = (whatever function JOptionPane uses to read input) this is susceptible to typos, as anything but yes or no will exit the loop, but without a bunch of extra code, it can't be helped.

    2. To add your numbers, use sum = sum + num

    3. To get the average, use AverageDivider = AverageDivider + 1
    near the end of each loop, after the user enters an integer. Then, after the loop, use Average = sum/AverageDivider

    If you are using the if/else statements I had in my code, remember to set num = 0 at the beginning of each loop. If you don't, all of your numbers will be the same, or it will allow you to type infinite lines of numbers without doing anything to them.(I forget which)

    I think thats all, if there is more, I will post the solution to that as well.
    Last edited by Singing Boyo; 03-23-2009 at 11:29 PM.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  12. #12
    himJ is offline Member
    Join Date
    Feb 2010
    Posts
    1
    Rep Power
    0

    Default

    please handle exceptions etc..can somebody tell me if the logic is okay..

    Java Code:
    import javax.swing.JOptionPane;
    
    class Sort3{
     
    public static void main(String args[]){
     
     String firstInput;
     String secondInput;
     String thirdInput;
     
     firstInput=JOptionPane.showInputDialog("enter your first number");
     secondInput=JOptionPane.showInputDialog("enter your second number");
     thirdInput=JOptionPane.showInputDialog("enter your third number");
    
     int i=Integer.parseInt(firstInput);
     int j=Integer.parseInt(secondInput);
     int k=Integer.parseInt(thirdInput);
     
     if(i>j)
       {if(i>k)
         {System.out.println(i);
           if(k>j)
            System.out.println(k+"\n"+j);
           else
            System.out.println(j+"\n"+k);
         }
        else 
         System.out.println(k+"\n"+i+"\n"+j);
       }
     else
       {if(j>k)
         {System.out.println(j);
           if(k>i)
            System.out.println(k+"\n"+i);
           else
            System.out.println(i+"\n"+k);
         }
        else 
         System.out.println(k+"\n"+j+"\n"+i);
       }
    }
    }
    Last edited by himJ; 02-19-2010 at 12:37 PM.

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,524
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by himJ View Post
    please handle exceptions etc..can somebody tell me if the logic is okay..

    Java Code:
     if(i>j)
       {if(i>k)
         {System.out.println(i);
           if(k>j)
            System.out.println(k+"\n"+j);
           else
            System.out.println(j+"\n"+k);
         }
        else 
         System.out.println(k+"\n"+i+"\n"+j);
       }
     else
       {if(j>k)
         {System.out.println(j);
           if(k>i)
            System.out.println(k+"\n"+i);
           else
            System.out.println(i+"\n"+k);
         }
        else 
         System.out.println(k+"\n"+j+"\n"+i);
       }
    }
    }
    I prefer this version:
    Java Code:
    int i,j,k; // the input values
    int si,sj,sk; // the sorted Values
    si= Math.min(i, Math.min(j, k));
    sk= Math.max(i, Math.max(j, k));
    sj= i^j^k^si^sk;
    kind regards,

    Jos

Similar Threads

  1. how to get the Integers out of a String
    By JordashTalon in forum New To Java
    Replies: 10
    Last Post: 01-30-2009, 06:28 PM
  2. Replies: 1
    Last Post: 10-20-2008, 07:55 PM
  3. Finding Median of X Integers
    By Hasan in forum New To Java
    Replies: 3
    Last Post: 08-12-2008, 02:06 PM
  4. Replies: 4
    Last Post: 04-16-2008, 01:26 PM
  5. Random Integers
    By www.kwalski.com in forum Java Applets
    Replies: 8
    Last Post: 12-09-2007, 05:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •