Commit c8362784 by Patryk Czarnik

Analiza 2

parent ba693fc6
package przyklady_dom;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class AnalizaWalut2 {
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser(".");
chooser.setFileFilter(new FileNameExtensionFilter("Pliki XML", "xml"));
chooser.setDialogTitle("Wybierz plik z walutami");
int wybor = chooser.showOpenDialog(null);
if(wybor != JFileChooser.APPROVE_OPTION){
return;
}
File wybranyPlik = chooser.getSelectedFile();
String szukanyKod = JOptionPane.showInputDialog("Podaj kod waluty", "USD");
if(szukanyKod == null) {
return;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
System.out.println("Mam DocumentBuilder: " + builder);
Document doc = builder.parse(wybranyPlik);
System.out.println("Dokument wczytany: " + doc);
Element root = doc.getDocumentElement();
System.out.println("Nazwa elememtu głównego: " + root.getTagName());
double suma = 0;
int ilosc = 0;
NodeList rates = root.getElementsByTagName("Rate");
final int nRates = rates.getLength();
for (int i = 0; i < nRates; i++) {
Element rate = (Element) rates.item(i);
// zakładamy, że każdy Rate na pewno posiada podelement Code; gdyby nie miał, to będzie wyjątek
Element elementCode = (Element) rate.getElementsByTagName("Code").item(0);
String code = elementCode.getTextContent();
if(code.equalsIgnoreCase(szukanyKod)) {
Element elementMid = (Element) rate.getElementsByTagName("Mid").item(0);
double mid = Double.parseDouble(elementMid.getTextContent());
suma += mid;
ilosc++;
}
}
double srednia = suma / ilosc;
JOptionPane.showMessageDialog(null,
String.format("Średni kurs waluty %s wynosi %.3f", szukanyKod, srednia));
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException(e);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment