OneCompiler

j6

243

/*
Write a Java program to accept ā€˜n’ integers from the user and store them in a Collection.
Display them in the sorted order. The collection should not accept duplicate elements.
(Use a suitable collection). Search for a particular element using predefined search
method in the Collection framework
*/
package com.mycompany.practical_slip;

import java.util.*;

public class slip6_1
{
public static void main(String[] args) {
TreeSet<Integer> nums = new TreeSet<>();
Scanner sc = new Scanner(System.in);

    System.out.println("How many number:");
    int n = sc.nextInt();
    System.out.println("Eneter " + n + " values:");
    for(int i=0; i<n; i++)
        nums.add(sc.nextInt());
    
    System.out.println(nums);
    
    System.out.println("Enter key to search:");
    int key = sc.nextInt();
    if(nums.contains(key))
        System.out.println("Found.");
    else
        System.out.println("Not found.");
}

}

/*
Write a java program using multithreading to simulate traffic signal (Use Swing).
*/
package com.mycompany.practical_slip;

import java.util.logging.*;

class TrafficLight implements Runnable {
String[] lights = {"Red", "Green", "Yellow"};

@Override
public void run() {
    int idx = 0;
    while(true) {
        System.out.println("Current Signal : " + lights[idx]);
        try {
            Thread.sleep(getDuration(lights[idx]) * 1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(TrafficLight.class.getName()).log(Level.SEVERE, null, ex);
        }
        idx = (idx + 1) % lights.length;
    }
}

private int getDuration(String light) {
    switch(light) {
        case "Red": return 4;
        case "Green": return 7;
        case "Yellow": return 2;
        default : return 0;
    }
}

}

public class slip6_2
{
public static void main(String[] args) {
Thread t = new Thread(new TrafficLight());
t.start();
}
}