Advertisement
brilliant_moves

TwoSmallest.java

Mar 7th, 2016
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.67 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.ArrayList;
  3.  
  4. public class TwoSmallest{
  5.  
  6.     public static double getRealNumber(Scanner in, double term, int count) {
  7.         System.out.println("enter real number");
  8.         double num = Double.parseDouble (in.nextLine());
  9.  
  10.         if (count>=2 && num==term) return num;
  11.  
  12.         while (num == term){
  13.             System.out.println(num+" [this is the terminating value, not part of the set of numbers]");
  14.             System.out.println("Enter different number: ");
  15.             num = Double.parseDouble (in.nextLine());
  16.         }
  17.         return num;
  18.     }
  19.  
  20.     public static void main(String[] args) {
  21.  
  22.         System.out.println("java TwoSmallest ");
  23.         System.out.println("type a terminating value (real number) ");
  24.         Scanner in = new Scanner(System.in);
  25.         ArrayList<Double> arl = new ArrayList<Double>();
  26.         double term = Double.parseDouble (in.nextLine());
  27.         System.out.println(term+" [this is the terminating value, not part of the set of numbers]");
  28.         double secondSmallest=0, smallest=0, num=0;
  29.         int count=0, index=0;
  30.         while(true) {
  31.             num = getRealNumber(in, term, count);
  32.             if (count>=2 && num==term) break;
  33.             while (num==term) {
  34.                 num = getRealNumber(in, term, count);
  35.             }
  36.             arl.add(num);
  37.             count++;
  38.         }
  39.         //System.out.println(arl.toString());
  40.         for (int i=0; i<arl.size(); i++) {
  41.             if (i==0 || arl.get(i)<smallest) {
  42.                 smallest = arl.get(i);
  43.                 index = i;
  44.             }
  45.         }
  46.         arl.remove(index); // remove the smallest number
  47.         for (int i=0; i<arl.size(); i++) {
  48.             if (i==0 || arl.get(i)<secondSmallest) {
  49.                 secondSmallest = arl.get(i);
  50.                 index = i;
  51.             }
  52.         }
  53.         System.out.println("\nSmallest = "+smallest);
  54.         System.out.println("Second smallest = "+secondSmallest);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement