Java malformed url exception for simple url

3.5k views Asked by At

Frustrating malformed url exception. As a test, i added the "URL url = new URL("http://www.google.com");" just to see if a very simple url would throw an error, and it does. I am lost as to what is causing this.

import javax.swing.*;
import java.net.*;

public class Train {

public static void main(String[] args) {
    URL url = new URL("http://www.google.com");
    ImageIcon icon = new ImageIcon(new URL("https://upload.wikimedia.org/wikipedia/commons/d/d4/Wikipedesketch1.png"));**
    Integer miles = Integer.parseInt(JOptionPane.showInputDialog("Enter the miles"));
    Double gallons = Double.parseDouble(JOptionPane.showInputDialog("Enter the gallons"));  
    Double mpg = miles / gallons;
    JOptionPane.showMessageDialog(null, "Miles per gallon is " + mpg, "Gass Mileage", JOptionPane.PLAIN_MESSAGE, icon); 
}

}

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type MalformedURLException Unhandled exception type MalformedURLException

at Train.main(Train.java:13)
1

There are 1 answers

6
Marvin On BEST ANSWER

You have compilation error and none of try/catch for Exception which throws new ImageIcon()

Try this:

import javax.swing.*;
import java.net.*;
public class Train {
    public static void main(String[] args) {
        try {
        URL url = new URL("http://www.google.com");
        ImageIcon icon = new ImageIcon(new URL("https://upload.wikimedia.org/wikipedia/commons/d/d4/Wikipedesketch1.png"));
        Integer miles = Integer.parseInt(JOptionPane.showInputDialog("Enter the miles"));
        Double gallons = Double.parseDouble(JOptionPane.showInputDialog("Enter the gallons"));  
        Double mpg = miles / gallons;
        JOptionPane.showMessageDialog(null, "Miles per gallon is " + mpg, "Gass Mileage", JOptionPane.PLAIN_MESSAGE, icon);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}