// Lösningar till tentamen, del B 2018-03-03 // Uppgift 1 import java.io.*; import java.util.*; class ObsProgram { public static void main(String[] arg) throws IOException { List l = new ArrayList<>(); Scanner fil = new Scanner(new File("obs.txt")); while (fil.hasNext()) { Observation obs = new Observation(); obs.nr = fil.nextInt(); obs.tid.tim = fil.nextInt(); obs.tid.min = fil.nextInt(); obs.temp = fil.nextDouble(); obs.vindhast = fil.nextDouble(); obs.vindrikt = fil.nextInt(); l.add(obs); } Collections.sort(l); for (Observation ob : l) System.out.println(ob.nr + " " + ob.tid + " " + ob.temp); Collections.sort(l,new JfrObs()); for (Observation ob : l) System.out.println(ob.nr + " " + ob.tid + " " + ob.temp); } } class JfrObs implements Comparator { public int compare(Observation o1, Observation o2) { if (o1.nr < o2.nr) return -1; else if (o1.nr == o2.nr) return o1.tid.compareTo(o2.tid); // i andra hand efter tid else return 1; } } // Uppgift 2 import java.util.*; interface Function { public double apply(double x); public static List MakeList(List a, Function f) { List b = new ArrayList<>(); for (Double d: a) b.add(f.apply(d)); return b; } } class Square implements Function { public double apply(double x) { return x*x; } } class Root implements Function { public double apply(double x) { return Math.sqrt(x); } } public static void main(String[] arg) { List l = new ArrayList<>(); Scanner s = new Scanner(System.in); while (s.hasNext()) l.add(s.nextDouble()); List kv = Function.MakeList(l, new Square()); List ro = Function.MakeList(l, new Root()); } } // Uppgift 3 import java.io.*; public class HistogramProg extends JFrame implements ActionListener { JMenuItem[] mi = {new JMenuItem("Show"), new JMenuItem("Hide"), new JMenuItem("Exit")}; Histogram h = new Histogram(); public HistogramProg() { JMenuBar mb = new JMenuBar(); setJMenuBar(mb); JMenu amen = new JMenu("Action"); mb.add(amen); for (JMenuItem it : mi) { amen.add(it); it.addActionListener(this); } add(h); setSize(500, 300); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void clear() { setTitle(null); remove(h); h = new Histogram(); add(h); repaint(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == mi[0]) { // Show clear(); String s = JOptionPane.showInputDialog("File name? "); if (s == null) // Stängningsrutan return; Scanner sc = null; try { sc = new Scanner(new File(s)); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "File not found"); return; } setTitle(s); while (sc.hasNextDouble()) h.addValue(sc.nextDouble()); } else if (e.getSource() == mi[1]) // Hide clear(); else if (e.getSource() == mi[2]) // Exit System.exit(0); }