Please Help - Secure Internet Programming

On Sun's home page at http://java.sun.com they have an article
on "Secure Internet Programming with JavaTM 2, Standard Edition (J2SETM) 1.4" so I tried it out but I got "cannot resolve symbol" compiler
error when I tried to compile HttpsServer.java - so what do I change
to get it to compile?
Here's the actual error message:
HttpsServer.java:32: cannot resolve symbol
symbol : class ServerSocketFactory
location: class HttpsServer
ServerSocketFactory ssf = sslcontext.getServerSocketFactory();
^
1 error
I'm using JDK1.4.1 but I can't believe that is the problem. Here is the
soucre code from the article:
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.*;
import java.util.StringTokenizer;
* This class implements a multithreaded simple HTTP
* server that supports the GET request method.
* It listens on port 44, waits client requests, and
* serves documents.
public class HttpsServer
String keystore = "serverkeys";
char keystorepass[] = "hellothere".toCharArray();
char keypassword[] = "hiagain".toCharArray();
//The port number which the server will be listening on
//*public static final int HTTP_PORT = 8080;
public static final int HTTPS_PORT = 443;
public ServerSocket getServer() throws Exception
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystore), keystorepass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keypassword);
SSLContext sslcontext = SSLContext.getInstance("SSLv3");
sslcontext.init(kmf.getKeyManagers(), null, null);
ServerSocketFactory ssf = sslcontext.getServerSocketFactory();
SSLServerSocket serversocket = (SSLServerSocket)ssf.createServerSocket(HTTPS_PORT);
//*return new ServerSocket(HTTP_PORT);
return serversocket;
//multi-threading -- create a new connection for each request
public void run()
ServerSocket listen;
try
listen = getServer();
while(true)
Socket client = listen.accept();
ProcessConnection cc = new ProcessConnection(client);
catch(Exception e)
System.out.println("Exception: "+e.getMessage());
//main program
public static void main(String argv[]) throws Exception
HttpsServer httpserver = new HttpsServer();
httpserver.run();
class ProcessConnection extends Thread
Socket client;
BufferedReader is;
DataOutputStream os;
public ProcessConnection(Socket s)
//constructor
client = s;
try
is = new BufferedReader(new InputStreamReader(client.getInputStream()));
os = new DataOutputStream(client.getOutputStream());
catch(IOException e)
System.out.println("Exception: "+e.getMessage());
this.start(); //Thread starts here...this start() will call run()
public void run()
try
//get a request and parse it.
String request = is.readLine();
System.out.println("Request: "+request);
StringTokenizer st = new StringTokenizer(request);
if((st.countTokens() >= 2) &&
st.nextToken().equals("GET"))
if((request = st.nextToken()).startsWith("/"))
request = request.substring(1);
if(request.equals(""))
request = request + "index.html";
File f = new File(request);
shipDocument(os, f);
else
os.writeBytes("400 Bad Request");
client.close();
catch(Exception e)
System.out.println("Exception: " + e.getMessage());
* Read the requested file and ships it
* to the browser if found.
public static void shipDocument(DataOutputStream out, File f) throws Exception
try
DataInputStream in = new
DataInputStream(new FileInputStream(f));
int len =(int) f.length();
byte[] buf = new byte[len];
in.readFully(buf);
in.close();
out.writeBytes("HTTP/1.0 200 OK\r\n");
out.writeBytes("Content-Length: " + f.length() +"\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.write(buf);
out.flush();
catch(Exception e)
out.writeBytes("<html><head><title>error</title></head><body>\r\n\r\n");
out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("</body></html>");
out.flush();
finally
out.close();

No problem, glad to help.
Sun, like anyone else, doesn't always catch typos and copy/paste errors. Hopefully next time something like this happens, you'll be able to understand the information that's available to you in the error message, and look in the documentation for help. That's the bigger lesson here.
Steve

Similar Messages

  • Please Help - Secure Internet

    On Sun's home page at http://java.sun.com they have an article
    on "Secure Internet Programming with JavaTM 2, Standard Edition (J2SETM) 1.4" so I tried it out but I got "cannot resolve symbol" compiler
    error when I tried to compile HttpsServer.java - so what do I change
    to get it to compile?
    Here's the actual error message:
    HttpsServer.java:32: cannot resolve symbol
    symbol : class ServerSocketFactory
    location: class HttpsServer
    ServerSocketFactory ssf = sslcontext.getServerSocketFactory();
    ^
    1 error
    I'm using JDK1.4.1 but I can't believe that is the problem. Here is the
    soucre code from the article:
    import java.io.*;
    import java.net.*;
    import javax.net.ssl.*;
    import java.security.*;
    import java.util.StringTokenizer;
    * This class implements a multithreaded simple HTTP
    * server that supports the GET request method.
    * It listens on port 44, waits client requests, and
    * serves documents.
    public class HttpsServer
         String keystore = "serverkeys";
         char keystorepass[] = "hellothere".toCharArray();
         char keypassword[] = "hiagain".toCharArray();
         //The port number which the server will be listening on
         //*public static final int HTTP_PORT = 8080;
         public static final int HTTPS_PORT = 443;
         public ServerSocket getServer() throws Exception
              KeyStore ks = KeyStore.getInstance("JKS");
              ks.load(new FileInputStream(keystore), keystorepass);
              KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
              kmf.init(ks, keypassword);
              SSLContext sslcontext = SSLContext.getInstance("SSLv3");
              sslcontext.init(kmf.getKeyManagers(), null, null);
              ServerSocketFactory ssf = sslcontext.getServerSocketFactory();
              SSLServerSocket serversocket = (SSLServerSocket)ssf.createServerSocket(HTTPS_PORT);
              //*return new ServerSocket(HTTP_PORT);
              return serversocket;
         //multi-threading -- create a new connection for each request
         public void run()
              ServerSocket listen;
              try
                   listen = getServer();
                   while(true)
                        Socket client = listen.accept();
                        ProcessConnection cc = new ProcessConnection(client);
              catch(Exception e)
                   System.out.println("Exception: "+e.getMessage());
         //main program
         public static void main(String argv[]) throws Exception
              HttpsServer httpserver = new HttpsServer();
              httpserver.run();
    class ProcessConnection extends Thread
         Socket client;
         BufferedReader is;
         DataOutputStream os;
         public ProcessConnection(Socket s)
              //constructor
              client = s;
              try
                   is = new BufferedReader(new InputStreamReader(client.getInputStream()));
                   os = new DataOutputStream(client.getOutputStream());
              catch(IOException e)
                   System.out.println("Exception: "+e.getMessage());
              this.start();                                                                            //Thread starts here...this start()     will call run()
         public void run()
              try
                   //get a request and parse it.
                   String request = is.readLine();
                   System.out.println("Request: "+request);
                   StringTokenizer st = new StringTokenizer(request);
                   if((st.countTokens() >= 2) &&
                   st.nextToken().equals("GET"))
                        if((request = st.nextToken()).startsWith("/"))
                             request = request.substring(1);
                        if(request.equals(""))
                             request = request + "index.html";
                        File f = new File(request);
                        shipDocument(os, f);
                   else
                        os.writeBytes("400 Bad Request");
                   client.close();
              catch(Exception e)
                   System.out.println("Exception: " + e.getMessage());
         * Read the requested file and ships it
         * to the browser if found.
         public static void shipDocument(DataOutputStream out, File f) throws Exception
              try
                   DataInputStream in = new
                   DataInputStream(new FileInputStream(f));
                   int len =(int) f.length();
                   byte[] buf = new byte[len];
                   in.readFully(buf);
                   in.close();
                   out.writeBytes("HTTP/1.0 200 OK\r\n");
                   out.writeBytes("Content-Length: " + f.length() +"\r\n");
                   out.writeBytes("Content-Type: text/html\r\n\r\n");
                   out.write(buf);
                   out.flush();
              catch(Exception e)
                   out.writeBytes("<html><head><title>error</title></head><body>\r\n\r\n");
                   out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
                   out.writeBytes("Content-Type: text/html\r\n\r\n");
                   out.writeBytes("</body></html>");
                   out.flush();
              finally
                   out.close();
    sou

    borntwice80, many thanks for your response - good idea
    but it turns out that all I needed was the following statement:
    import javax.net.*;                                                       
    ...and that fixed the problem
    ...Actually, it was mutmansky in the java programming forum
    that found it.

  • Please help find the program

    Please help find the program to block unwanted number, call and SMS, that not all block number ,but  the number on which you want to.

    Which part of "The 5310 is just a java phone that cannot support applications like this." did you not understand?
    If you want to achieve any form of blocking at all, it won't be with that phone. Your operator may be able to help by putting a block in place on their end, though, but I doubt it.
    Was this post helpful? If so, please click on the white "Kudos!" star below. Thank you!

  • Please help me this program

    Please help me with this program,the progarm should operates as follows
    1)Calculate the number of words
    2)Calculate the number of sentences
    3)Calculate the repeated words
    * Title: <p>
    * Description: <p>
    * Copyright: Copyright (c) cds<p>
    * Company: s<p>
    * @author cds
    * @version 1.0
    package count;
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.border.*;
    import java.util.StringTokenizer;
    public class Frame1 extends JFrame {
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    XYLayout xYLayout2 = new XYLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JTextArea jta1 = new JTextArea();
    JScrollPane jScrollPane2 = new JScrollPane();
    JTextArea jta2 = new JTextArea();
    JLabel jLabel1 = new JLabel();
    JLabel jLabel2 = new JLabel();
    JButton jbtCountSentances = new JButton();
    JButton jbtCountWords = new JButton();
    JButton jbtRWords = new JButton();
    JButton jbtClearList = new JButton();
    JTextField jtfNumOfSentances = new JTextField();
    JLabel jLabel3 = new JLabel();
    JLabel jLabel4 = new JLabel();
    JTextField jtfNumOfWords = new JTextField();
    private JFileChooser jFileChooser = new JFileChooser();
    public static String sentence,RepeatedWords,repwords,chr=" ";
         public static int i,words,token,periods,characters,len,long_word,long_sent,stop;
    //Construct the frame
    public Frame1() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    }setSize(600,400);
    show();
    public static void main(String[] args) {
    Frame1 frame1 = new Frame1();
    private void jbInit() throws Exception {
    jPanel1.setLayout(xYLayout1);
    this.getContentPane().setLayout(xYLayout2);
    jLabel1.setForeground(Color.blue);
    jLabel1.setText(" Type your Doc");
    jLabel2.setForeground(Color.blue);
    jLabel2.setText(" Reapeated Words");
    jbtCountSentances.setBackground(Color.white);
    jbtCountSentances.setForeground(Color.blue);
    jbtCountSentances.setText("Count Sentances");
    jbtCountSentances.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtCountSentances_actionPerformed(e);
    jbtCountWords.setBackground(Color.white);
    jbtCountWords.setForeground(Color.blue);
    jbtCountWords.setText("Count Words");
    jbtCountWords.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtCountWords_actionPerformed(e);
    jbtRWords.setBackground(Color.white);
    jbtRWords.setForeground(Color.blue);
    jbtRWords.setText("Reapeted Words");
    jbtRWords.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtRWords_actionPerformed(e);
    jbtClearList.setBackground(Color.white);
    jbtClearList.setForeground(Color.blue);
    jbtClearList.setText("Clear");
    jbtClearList.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jbtClearList_actionPerformed(e);
    jLabel3.setForeground(Color.blue);
    jLabel3.setText("NumOfSentances");
    jLabel4.setForeground(Color.blue);
    jLabel4.setText("NumOfWords");
    jPanel1.setBackground(SystemColor.activeCaption);
    jPanel1.setForeground(SystemColor.activeCaption);
    this.getContentPane().add(jPanel1, new XYConstraints(4, 4, 986, 469));
    jPanel1.add(jScrollPane1, new XYConstraints(5, 105, 289, 192));
    jScrollPane1.getViewport().add(jta1, null);
    jPanel1.add(jScrollPane2, new XYConstraints(309, 102, 256, 193));
    jScrollPane2.getViewport().add(jta2, null);
    jPanel1.add(jLabel1, new XYConstraints(21, 81, 240, 22));
    jPanel1.add(jLabel2, new XYConstraints(340, 78, 191, 20));
    jPanel1.add(jbtCountSentances, new XYConstraints(69, 309, 190, 30));
    jPanel1.add(jbtCountWords, new XYConstraints(69, 339, 190, 24));
    jPanel1.add(jbtClearList, new XYConstraints(262, 337, 173, 26));
    jPanel1.add(jbtRWords, new XYConstraints(262, 310, 174, 24));
    jPanel1.add(jLabel3, new XYConstraints(14, 37, 105, 20));
    jPanel1.add(jtfNumOfSentances, new XYConstraints(114, 37, 64, 23));
    jPanel1.add(jLabel4, new XYConstraints(212, 38, 82, 23));
    jPanel1.add(jtfNumOfWords, new XYConstraints(304, 35, 83, 27));
    void jbtCountSentances_actionPerformed(ActionEvent e) {
    BufferedReader stdin = new BufferedReader
                   (new InputStreamReader (System.in));
    sentence = jta1.getText();
              System.out.flush ();
              len=sentence.length();
    jtfNumOfSentances.setText(String.valueOf(num_periods()));
    public static int num_periods () {
              i=0;
              periods=3;
              chr= ".";
    chr= "!";
    chr= "?";
              while (i<len){
                   if (sentence.charAt(i)==chr.charAt(0))
                        periods++;
                   i++;
         return periods;
         }//Method num_words
    void jbtCountWords_actionPerformed(ActionEvent e) {
    String s = jta1.getText();
    StringTokenizer st = new StringTokenizer(s);
    jtfNumOfWords.setText(String.valueOf(st.countTokens()));
    void jbtRWords_actionPerformed(ActionEvent e) {
    repwords = jta1.getText();
    StringTokenizer st = new StringTokenizer(repwords);
              while (st.hasMoreTokens())
    RepeatedWords = st.nextToken(st.toString()) ;
         jta2.append(RepeatedWords);
         //}//Method num_words
    /*void jbtClearList_actionPerformed(ActionEvent e) {
    jta2.setText(null);
    void jbtHelp_actionPerformed(ActionEvent e) {
    jta1.append("Please open a File Write a document");
    // JScrollPane jScrollPane1 = new JScrollPane();
    //JTextArea jta1 = new JTextArea();
    // JScrollPane jScrollPane2 = new JScrollPane();
    //JTextArea jta2 = new JTextArea();
    void jbtClearList_actionPerformed(ActionEvent e) {
    jta2.setText(null);
    jta1.setText(null);
    jtfNumOfWords.setText(null);
    jtfNumOfSentances.setText(null);

    Let me try specify the main problem in details
    The code that i had posted displays an interface consisting of a 2 textarea.
    The first textarea is for a user to enter a sentence and the second is for displaying duplicated words.
    The program should allow the user to enter a sentence on the first textarea and when JButton named showduplicatedwords pressed it must display the words that are being duplicated in the sentence on the second textarea.And again count the number of sentence available when
    JButton countsentence is pressed

  • Hi i am not able to retrieve web/internet history please help. my Internet service provider advise me to contact you.

    for some reason i am not able to retrieve or view my web/internet history please help

    Is the history enabled?
    To see all History and Cookie settings, choose:
    *Tools > Options > Privacy > Firefox will: "Use custom settings for history"
    *https://support.mozilla.org/kb/Options+window+-+Privacy+panel
    Do you see any history in the History Manager (Library; Show All history)?
    *Tap the Alt key or press F10 to show the Menu Bar
    There is also a History button in the "3-bar" Firefox menu button drop-down list.

  • Please help with internet problems

    Hi
    I have just started having problems with my blackberry curve. When i go to internet and click on my bookmarks it opens up front page fine but when i try to click on pages to connect to from front page it kicks me out straight to bookmarks page. Please help ????????????> this has only started in last few days i.e i go to sky sports which it opens then trying to click on an item to read it kicks me straight to bookmarks page????????

    Hi cp70uk
    Welcome to BlackBerry Support Forums
    Have you try Clearing your device Browser data ,you can try this and see if that helps ,For that Open your Browser > Press  the Menu key > Scroll down to Clear Browser Data ( Mark all fiels ) then Clear Now .
    Then perform a Battery Pull Restart like this device POWERED ON remove the battery wait for a min. then reinsert it back ,after reboot see if problem resolves.
    Click " Like " if you want to Thank someone.
    If Problem Resolves mark the post(s) as " Solution ", so that other can make use of it.

  • PLEASE HELP making a program that uses sudo commands

    hey
    is there anyway to make a program run sudo commands
    i have a problem because in a terminal it would ask you to input a password.
    is there a way to use a fake keyboard program to input the password in the back ground
    of my java application or some how run sudo commands? my application relies on some outputs of these commands.
    please help thanks.

    ill tell you a bit about my program im making.
    i have a wireless usb that i have to switch back and forth to get my paticullar drivers to
    do certain things e.g. one is for web browsing and the other one has packet injection.
    by typing sudo modprobe ect.. i can switch through a terminal. which requires me to type in a password.
    iv made a application which uses the
    Runtime.getRuntime().exec("sudo ...."); it has 2 buttons to switch from diffrent drivers and always runs at start up.
    just a big problem i cant use sudo it just freezes when i start and click on the buttons. and doesnt ask me for a password.
    can anyone help thanks

  • Please help on this program

    Dear Friends,
    With the help of this program I am trying to connect two instruments (One is CM110 monochromator of Spectral products and another one is from Keithley 2400 source meter) with the same programs. With the help of this program I am trying to increase the wavelength of the monochromator by say 10 nm and want to read the current at applied source meter voltage. 
    But the problem is each execution of while loop it is keeping ON/OFF the souce meter applied voltage . I want to keep the applied source meter voltage on through out the whole while loop and read the current, but I am not able to do so.
    Please help me. For your further information I am attaching the LabVIEW Program.
    Thanks in anticipation
    Regards
    Upendra Pandey
    Attachments:
    p2_for_1.vi ‏25 KB

    Chemical,
    You may want to try initializing and closing the Keithley outside of the main loop.  Regards, -SS 

  • Please help in createImage program

    Hi,
    Following is the code for drawing rectangle using java.awt.Graphics class.
    Problem is it is only displaying frame not the rectangle.what's wroung with this?
    I am using Image because I need to store the ractangle as a image.Once image is created I can use gifencoder or jpegencoder classes.
    I need to solve this soon , I am stuck in the project..please help me out.
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.Frame;
    import java.awt.Color;
    import javax.swing.*;
    import java.awt.Component;
    public class SaveImage
    public static void main(String arg[])
    //JFrame f=new JFrame("Save Image");
    Component dummy;
    dummy= new JFrame("Save Image");
    dummy.addNotify();
    Image img=dummy.createImage(200,200);
    Graphics g=img.getGraphics();
    g.setColor(Color.yellow);
    g.fillRect(20,20,100,100);
    g.drawOval(20,45,25,25);
    dummy.setSize(500,500);
    dummy.setVisible(true);
    Thanks,
    padmashree

    Thanks for you feedback.
    i dont know what u want with the Image???I need Image because , I have to store the the daigram into file like in .jpeg or .bmp format which we need for later use.
    I was thinking of using JpegEncoder class. I have downloded the class. Before using that I need to create image first and getGraphics() from image then draw diagram.
    I realy don't know how createImage method works and on which object needs to be invoked? Do you?
    I have checked on forum I saw someone's code to create image , whichis something like this
    Component dummy;
    dummy=new Frame();
    Image img=dummy.createImage(500,500); OR just Image img=createImage(500,500);
    Graphics g=img.getGraphics();
    g.drawRectangle(200,200,400,400);
    If I use this code in paint( ...g) method I am getting errot and it's not painting .
    I have changed the code like,
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.Frame;
    import java.awt.Color;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.event.*;
    public class SaveImage extends JFrame
    Image img;
    public SaveImage()
    super("Save Image");
    img=createImage(300,300);
    setSize(500,500);
    show();
    public static void main(String [] args)
    SaveImage app = new SaveImage();
    System.out.println("Within main");
    System.out.println("After Paint");
    public void paint(Graphics g)
    System.out.println("Within Paint");
    g=img.getGraphics();
    g.setColor(Color.yellow);
    g.fillRect(20,20,100,100);
    g.drawOval(20,45,25,25);
    repaint();
    Please help me in this I am stuck in the project from yestarday.
    Thanks,
    Padmashree
    but you can just copy what the graphics paints onto
    the frame into an img and then to a file
    hope it helps
    import java.awt.Image;
    import java.awt.Graphics;
    import java.awt.Frame;
    import java.awt.Color;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.event.*;
    public class SaveImage extends JFrame
    public SaveImage()
    super("Save Image");
    setSize(500,500);
    show();
    public static void main(String [] args)
    SaveImage app = new SaveImage();
    app.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void paint(Graphics g)
    g.setColor(Color.yellow);
    g.fillRect(20,20,100,100);
    g.drawOval(20,45,25,25);
    repaint();

  • Please Help: no internet on MBP (10.8.3) via iPhone 5 (6.1.4) personal hotspot, usb or bluetooth

    Hello all,
    I used to be able to get Internet on my MBP (mid 2009 13, OSX 10.8.3) through iPhone 5 (ios 6.1.4) using either USB or bluetooth. Now, the personal hotspot LINK between my MBP and Iphone via bluetooth is ACTIVE (the blue bar says there's a connection), but there's NO INTERNET CONNECTION. USB tethering doesn't work at all (no blue bar).
    Because the personal hotpot still works between my iPhone 5 and iPad 2, I suspect that the problem is with my mac. I've tried re-pairing my Mac and the phone a couple of times. I've reset iPhone network settings. Nothing I tried helped. Can someone help please?
    Thanks, Shiang

    I was asking whether you could tether via Wi-Fi. I take it that you can't.
    Run the Network Diagnostics assistant. How far do you get?

  • Can anyone please help with my program?

    I know, I know. It's another Mortgage Calculator question. I'm sure you all are sick of them. But I don't know where else to turn, our instructor is not helpful at all and never even bothers to respond to our questions.
    Anyway so the assignment is:
    Write the program in Java (with a graphical user interface) so that it will allow the user to select which way they want to calculate a mortgage: by input of the amount of the mortgage, the term of the mortgage, and the interest rate of the mortgage payment or by input of the amount of a mortgage and then select from a menu of mortgage loans:
    - 7 year at 5.35%
    - 15 year at 5.5 %
    - 30 year at 5.75%
    In either case, display the mortgage payment amount and then, list the loan balance and interest paid for each payment over the term of the loan. Allow the user to loop back and enter a new amount and make a new selection, or quit. Insert comments in the program to document the program.
    Here is what I have so far:
    import java.text.*;
    import java.math.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class MortgageCalcv7 extends javax.swing.JFrame
        //new form creation
             public MortgageCalcv7()
                    initComponents();
                    setLocation(400,250);
        // New method to initialize the form
        private void initComponents()// starts the java components initialization
            amtofloan = new javax.swing.JLabel();
            text1 = new javax.swing.JTextField();
            term = new javax.swing.JLabel();
            radiobutt1 = new javax.swing.JRadioButton();
            radiobutt2 = new javax.swing.JRadioButton();
            radiobutt3 = new javax.swing.JRadioButton();
            calculatebutt1 = new javax.swing.JButton();
            amt1 = new javax.swing.JLabel();
            panescroll = new javax.swing.JScrollPane();
            textarea1 = new javax.swing.JTextArea();
            quitbutt1 = new javax.swing.JButton();
            clearbutton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("McBride Financial Services Mortgage Calculator"); //displays title bar text
            amtofloan.setText("Enter the dollar amount of your Mortgage:"); // text area title for where user puts dollar amount of mortgage
            term.setText("Select Your Term and Interest Rate:"); // text area title for where user puts in term and interest rate selection
            radiobutt1.setText("7 years at 5.35% interest"); // sets button text for first radio button
            radiobutt1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); // sets border for radiobutt1
            radiobutt1.setMargin(new java.awt.Insets(0, 0, 0, 0)); // sets margin for radiobutt1
            radiobutt1.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent e) // class for action event
                    radiobutt1ActionPerformed(e);
            radiobutt2.setText("15 years at 5.5% interest");// sets button text for second radio button
            radiobutt2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); // sets border for radiobutt2
            radiobutt2.setMargin(new java.awt.Insets(0, 0, 0, 0)); // sets margin for radiobutt2
            radiobutt2.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent e) // class for action event
                    radiobutt2ActionPerformed(e);
            radiobutt3.setText("30 years at 5.75% interest");// sets button text for third and final radio button
            radiobutt3.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));// sets border for radiobutt3
            radiobutt3.setMargin(new java.awt.Insets(0, 0, 0, 0));// sets margin for radiobutt3
            radiobutt3.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent e)// class for action event
                    radiobutt3ActionPerformed(e);
            calculatebutt1.setText("Submit"); // submit button text
            calculatebutt1.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent e)
                    calculatebutt1ActionPerformed(e);
              // sets text area size
            textarea1.setColumns(20);
            textarea1.setEditable(false);
            textarea1.setRows(5);
            panescroll.setViewportView(textarea1);
            quitbutt1.setText("Quit"); // quit button text
            quitbutt1.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent e)
                    quitbutt1ActionPerformed(e);
         //layout
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(26, 26, 26)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(panescroll, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(amt1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 222, Short.MAX_VALUE)
                                .addComponent(calculatebutt1)
                                .addGap(75, 75, 75))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(radiobutt3)
                                    .addComponent(radiobutt2)
                                    .addComponent(radiobutt1)
                                    .addComponent(term)
                                    .addComponent(amtofloan)
                                    .addComponent(text1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(224, Short.MAX_VALUE)))))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(277, Short.MAX_VALUE)
                    .addComponent(quitbutt1)
                    .addGap(70, 70, 70))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(31, 31, 31)
                    .addComponent(amtofloan)
                    .addGap(14, 14, 14)
                    .addComponent(text1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20)
                    .addComponent(term)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(radiobutt1)
                    .addGap(15, 15, 15)
                    .addComponent(radiobutt2)
                    .addGap(19, 19, 19)
                    .addComponent(radiobutt3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(calculatebutt1)
                        .addComponent(amt1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(panescroll, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addGap(18, 18, 18)
                    .addComponent(quitbutt1)
                    .addGap(20, 20, 20))
            pack();
        } // Ends java components initialization
        private void quitbutt1ActionPerformed(java.awt.event.ActionEvent e)
        {// starts event_quitbutt1ActionPerformed
            System.exit(1);
        }// starts event_quitbutt1ActionPerformed
        static NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
        static NumberFormat np = NumberFormat.getPercentInstance();
        static NumberFormat ni = NumberFormat.getIntegerInstance();
        static BufferedReader br;
        private void calculatebutt1ActionPerformed(java.awt.event.ActionEvent e)
        { // starts event_calculatebutt1ActionPerformed
        public void actionToBePerformed(ActionEvent e)
         if ("Clear". equals(e.getActionCommand())
         calculatePayment();
         else if
         amtofloan.settext("");
         intrst.settext("");
         loanspan.settext("");
         monthlypayments.settext("");
         rate.settext("");
         term.settext("")
         intRate=Integer.parseInt(Rate.showtext());
         DecimalFormat money = new DecimalFormat("$0.00");
            amt1.setText(null);
            textarea1.setText(null);
            double pmntamt;
            double intrst;
            double amounnt1;
            int loanspan;
            double interestmonthly, principlemonthly, balanceofloan;
            int balanceremainder, amtoflines;
            np.setMinimumFractionDigits(2);
        br = new BufferedReader(new InputStreamReader(System.in));
      amtoflines = 0;
            try
                    amounnt1=Double.parseDouble(text1.getText());
            catch (Exception evt)
                amt1.setText("Enter total amount due on mortgage");
                return;
            if(radiobutt1.isSelected())
                intrst=0.0535;
                loanspan=7;
            else if(radiobutt2.isSelected())
                intrst=0.055;
                loanspan=15;
            else if(radiobutt3.isSelected())
                intrst=0.0575;
                loanspan=30;
            else
                amt1.setText("Select term of loan and interest rate");
                return;
        textarea1.append(" For mortgage amount " + nf.format(amounnt1)+"\n"+" with mortgage term " + ni.format(loanspan) + " years"+"\n"+" and interest rate of " + np.format(intrst)+"\n"+" the monthly payment is " + nf.format(getMortgagePmt(amounnt1, loanspan, intrst))+"\n"+"\n");
        balanceofloan = amounnt1 - ((getMortgagePmt(amounnt1, loanspan, intrst)) - (amounnt1*(intrst/12)));
        balanceremainder = 0;
        do
            interestmonthly = balanceofloan * (intrst/12);// monthly interest
             principlemonthly = (getMortgagePmt(amounnt1, loanspan, intrst)) - interestmonthly;//*Principal payment each month minus interest
            balanceremainder = balanceremainder + 1;
            balanceofloan = balanceofloan - principlemonthly;//remaining balance
            textarea1.append(" Principal on payment  " + ni.format(balanceremainder) + " is " + nf.format(principlemonthly)+"\n");
                    textarea1.append(" Interest on payment  " + ni.format(balanceremainder) + " is " + nf.format(interestmonthly)+"\n");
                    textarea1.append(" Remaining balance on payment  " + ni.format(balanceremainder) + " is " + nf.format(balanceofloan)+"\n"+"\n"+"\n");
         while (balanceofloan > 1);
        }// starts event_jRadioBtton1Action Performed
        public static double getMortgagePmt(double balance, double term, double rate)
                double monthlyRate = rate / 12;
                double pmntamt = (balance * monthlyRate)/(1-Math.pow(1+monthlyRate, - term * 12));
                return pmntamt;
        private void radiobutt3ActionPerformed(java.awt.event.ActionEvent e)
        {// starts event_radiobutt3ActionPerformed
             if(radiobutt2.isSelected())
                radiobutt2.setSelected(false);
             if(radiobutt1.isSelected())
                radiobutt1.setSelected(false);
        }// ends event_radiobutt3ActionPerformed
        private void radiobutt2ActionPerformed(java.awt.event.ActionEvent e)
        {// starts event_radiobutt2ActionPerformed
             if(radiobutt1.isSelected())
                radiobutt1.setSelected(false);
             if(radiobutt3.isSelected())
                radiobutt3.setSelected(false);
        }// ends event_radiobutt2ActionPerformed
        private void radiobutt1ActionPerformed(java.awt.event.ActionEvent e)
        {// starts event_radiobutt1ActionPerformed
            if(radiobutt2.isSelected())
                radiobutt2.setSelected(false);
            if(radiobutt3.isSelected())
                radiobutt3.setSelected(false);
        }// ends event_radiobutt1ActionPerformed
        public static void main(String args[]) //main method start
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    new MortgageCalcv7().setVisible(true);
        // declares variables
        private javax.swing.JButton calculatebutt1;
        private javax.swing.JButton quitbutt1;
        private javax.swing.JButton clearbutton;
        private javax.swing.JLabel amtofloan;
        private javax.swing.JLabel term;
        private javax.swing.JLabel amt1;
        private javax.swing.JRadioButton radiobutt1;
        private javax.swing.JRadioButton radiobutt2;
        private javax.swing.JRadioButton radiobutt3;
        private javax.swing.JScrollPane panescroll;
        private javax.swing.JTextArea textarea1;
        private javax.swing.JTextField text1;
    } //end MortgageCalcv7.javaEverything was fine until I tried to add the clear button. Now it won't compile and gives me the following errors. Please if you could find it in your kind heart to help a girl out, I would be forever in your debt. Thanks in advance!
    MortgageCalcv7.java:211: illegal start of expression
    public void actionToBePerformed(ActionEvent e)
    ^
    MortgageCalcv7.java:213: ')' expected
         if ("Clear". equals(e.getActionCommand())
         ^
    MortgageCalcv7.java:218: '(' expected
         else if
         ^
    MortgageCalcv7.java:219: illegal start of expression
         ^
    MortgageCalcv7.java:225: ';' expected
         term.settext("")
         ^
    MortgageCalcv7.java:291: illegal start of expression
    public static double getMortgagePmt(double balance, double term, double rate)
    ^
    6 errors
    Edited by: cheesegoddess on Oct 12, 2008 7:49 AM

    You guys were very helpful, thank you! Thank you so very much!! The others needed braces somewhere and I took else out and that line compiles now. Thank you, thank you, thank you.
    I am down to 1 error now. I cannot find where there is a missing bracket, if that is the problem.
    The line erring is:
    211    public void actionToBePerformed(ActionEvent e)and the error I am still getting is:
    MortgageCalcv7.java:211: illegal start of expression
    public void actionToBePerformed(ActionEvent e)
    ^
    Any ideas? TIA.

  • PLEASE HELP! INTERNET CONNECTION PROBLEMS....

    Hey guys!
    I just got myself a brand new itouch last week (I'm SO excited), the problem is this, i cannot get it to connect to the internet! I've got a wired connection, and i need to know how to either change everything over to wireless (which would be an expensive pain as I've got a HD tivo, a Wii, an xbox 360, plus my computed that are using up everything on my router) or somehow get a wireless router connected to all of this somehow...my cable modem has only one output, too. So, I feel TOTALLY helpless! Maybe there is something I'm missing or not thinking of or something, but I'm so frustrated! I love my itouch and want to definitely keep it but...how do i get it to connect to the internet? Sorry about the rambling message...Thanks for listening...
    ~joey~

    While an Apple Airport is a very nice router (and is clearly very Mac friendly in terms of setup and such), it is expensive.
    You could achieve the same results - a wireless connection for your Touch - with a low-end wireless router from Belkin, Netgear, Linksys, etc. You only need 802.1 g/b (i.e., some of the newer, "faster" access protocol won't work on the Touch anyway), so you could go with some of the lowest-end offerings from these other manufacturers. Generally, such things are available from office supply (e.g., Staples) or big box (e.g., Best Buy) stores for under $50. You could also search somewhere like Craigslist and find and older one (that someone is upgrading from) for for next to free. If nesc, go to the maker's website to download a manual once you have a used piece of equip. Since you seem to be a PC (windows) user, you should be able to run the setup programs on the manuf-supplied CDs for most anything that you find.
    In most cases, you can bridge your "new" wireless router to the wired router, thereby keeping your wired router fully in place. Or, you may be able to swap everything over to the wireless router (using its wired ports...most wireless routers have a least 4 wired ports...for those devices you have that aren't wireless). Depending on what you get for a wireless router, you have a variety of options.
    Hope this helps.

  • Please help with my program

    I'm a newbie, i wrote a simple dictanary program, but i can't make it run properly. there are no errors but there is a problem...
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.regex.*;
    public class Dictionary{
    public static void main(String args[]){
    DicWin dic = new DicWin("Dictionary");
    class DicWin extends Frame implements ActionListener{
    Panel[] panels = new Panel[2];
    private static String REGEX = "^";
    Button ok;
    TextField text;
    String[] words;
    TextArea textF;
    public DicWin(String title){
         super(title);
         ReadDic("Mueller24.txt");
         setLayout(new GridLayout(2,1));
         panels[0] = new Panel();
         panels[1] = new Panel();
         First(panels[0]);
         Second(panels[1]);
         add(panels[0]);
         add(panels[1]);
         pack();
         setVisible(true);
    public void First(Container con){
         ok = new Button("OK");
         text = new TextField(20);
         con.add(ok);
         ok.addActionListener(this);
         con.add(text);
    public void Second(Container con){
         textF = new TextArea(5,20);
         con.add(textF);
    public void actionPerformed(ActionEvent e)
    String text2 = text.getText();
    Pattern p = Pattern.compile(REGEX + text2);
    for(int j=0;j<words.length;j++){
    Matcher m = p.matcher(words[j]);
    if(m.find())
         textF.setText(textF.getText() + "\n" + words[j]);
    private void ReadDic (String FileName){
    String line;
    int i=0;
    BufferedReader in = null;
    try{
    in = new BufferedReader(new FileReader("Mueller24.txt"));
         while((line = in.readLine())!=null)
         i++;
         words = new String;
         i=0;
         while((line = in.readLine())!=null)
         words[i]=line;
         i++;
    catch(IOException e){
    System.out.println("Error Loading the file.");

    Please make the ReadDic() method as following.
    private void ReadDic(String FileName) {
    String line;
    int i = 0;
    BufferedReader in = null;
    try {
    in = new BufferedReader(new FileReader("Mueller24.txt"));
    while ((line = in.readLine()) != null) {
    i++;
    words = new String[10];
    i = 0;
    while ((line = in.readLine()) != null) {
    words[i] = line;
    i++;
    } catch (IOException e) {
    System.out.println("Error Loading the file.");
    Please notice the line
    words = new String;
    in your original program should be something like following,
    words = new String[10]
    and the line,
    words = line;
    should be
    words[i] = line;
    I hope this would help.
    Pramoda

  • Please help with common program!!

    First I want to say that I did search to forum and I have not found a roman numeral conversion program written with a user defined class. Im not good with the terminology but the two programs are "working together" however I cannot get the output to print properly.......so maybe they arent working together. Anyway here is my code for the two and the output I am getting. The program is to convert a roman numeral to an integer value.
       public class Roman
           public static int numeralToInt(char ch)
             switch(ch)
                case 'M':
                   return 1000;
                case 'D':
                   return 500;
                case 'C':
                   return 100;
                case 'L':
                   return 50;
                case 'X':
                   return 10;
                case 'V':
                   return 5;
                case 'I':
                   return 1;
                case '0':
                   return 0;
             return 0;
    import java.util.*;
       import javax.swing.JOptionPane;
       import java.io.*;
       import javax.swing.*;
        public class RomanMain extends Roman
          static Scanner console =new Scanner(System.in);
           public static void main(String[]args)
                              throws FileNotFoundException, InputMismatchException
             Roman r=new Roman();
             System.out.println("Please enter a Roman Numeral for Conversion");
             console.next();   
             System.out.println("The converted value is:"+r);
       }This is very basic, all I am trying to do right now is get the correct output. I have tested it just by using M which should equal 1000. However I get the following.
    The converted value is:Roman@173831bThanks in advance
    Robert

    Im not even gonna respond to your question db. I go to class 15 hours a week work 40 and spend another 20 studying for my OOP class and writing code, as well ascountless hours on my other homework. I work my ass off and when I get hung up I come here and read API's and browse forums archives looking for answers and when all else fails I come to the forums and ask. I've learned through surfing all these forums that most of you are assholes and have no interest in helping people. In fact most of you come off as thought the only reason you are here is cuase your self proclaimed java experts and you want all us newbies to bow down to you. I do appreciate everyone here that is not an asshole for helping, but anyone else that is just a total fuckwad can piss off. DB next time try asking a question without accusing someone of copying code.
    Once again thanks to everyone that is polite about helping people. Im sure i violated teh code of conduct but if i dont get kicked out of here for good, when i get better at java I'm gonna devote time to helping students and not being a dickhead. Until then Adios I'm off to a forum that is helpful and not demeaning.
    Robert

  • Please help with Java program

    Errors driving me crazy! although compiles fine
    I am working on a project for an online class - I am teaching myself really! My last assignment I cannot get to work. I had a friend who "knows" what he is doing help me. Well that didn't work out too well, my class is a beginner and he put stuff in that I never used yet. I am using Jgrasp and Eclipse. I really am trying but, there really is no teacher with this online class. I can't get questions answered in time and stuff goes past due. I am getting this error:
    Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader .java:55)
    at java.util.Scanner.<init>(Scanner.java:590)
    at ttest.main(ttest.java:54)
    ----jGRASP wedge2: exit code for process is 1.
    ----jGRASP: operation complete.
    This is my code:
    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    The assignment is:
    Create a Java program to read in an unknown number of lines from a data file. You will need to create the data file. The contents of the file can be found at the bottom of this document. This file contains a football team's name, the number of games they have won, and the number of games they have lost.
    Your program should accomplish the following tasks:
    1. Process all data until it reaches the end-of-file. Calculate the win percentage for each team.
    2. Output to a file ("top.txt") a listing of all teams with a win percentage greater than .500. This file should contain the team name and the win percentage.
    3. Output to a file ("bottom.txt") a listing of all teams with a win percentage of .500 or lower. This file should contain the team name and the win percentage.
    4. Count and print to the screen the number of teams with a record greater then .500 and the number of teams with a record of .500 and below, each appropriately labeled.
    5. Output in a message box: the team with the highest win percentage and the team with the lowest win percentage, each appropriately labeled. If there is a tie for the highest win percentage or a tie for the lowest win percentage, you must output all of the teams.
    Dallas 5 2
    Philadelphia 4 3
    Washington 3 4
    NY_Giants 3 4
    Minnesota 6 1
    Green_Bay 3 4

    import java.util.*;
    import java.io.*;
    public class ttest
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)throws IOException
    FileInputStream fin = null; // input file reference
    PrintStream floser = null; // output file references
    PrintStream fwinner = null;
    Scanner rs; // record scanner
    Scanner ls; // line scanner
    String inputrec; // full record buffer
    int wins; // data read from each record
    int losses;
    double pctg;
    String team;
    String best = null; // track best/worst team(s)
    String worst = null;
    double worst_pctg = 2.0; // track best/worst pctgs
    double best_pctg = -1.0;
    int winner_count = 0; // counters for winning/losing records
    int loser_count = 0;
    // should check args.length and if not == 1 generate error
    try
    Scanner inFile = new Scanner(new FileReader("football.txt"));
    catch( FileNotFoundException e )
    System.exit( 1 );
    try
    floser = new PrintStream( new FileOutputStream( "loser.txt" ) );
    fwinner = new PrintStream( new FileOutputStream( "winner.txt" ) );
    catch( FileNotFoundException e )
    System.out.printf( "unable to open an output file: %s\n", e.toString() );
    System.exit( 1 );
    try
    rs = new Scanner( fin );
    while( rs.hasNext( ) )
    inputrec = rs.nextLine( ); /* read next line */
    ls = new Scanner( inputrec ); /* prevents stumble if record has more than expected */
    team = ls.next( );
    wins = ls.nextInt();
    losses = ls.nextInt();
    if( wins + losses > 0 )
    pctg = ((double) wins)/(wins + losses);
    else
    pctg = 0.0;
    if( pctg > .5 )
    if( pctg > best_pctg )
    best_pctg = pctg;
    best = team;
    else
    if( pctg == best_pctg )
    best += ", " + team;
    fwinner.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    winner_count++;
    else
    if( pctg < worst_pctg )
    worst_pctg = pctg;
    worst = team;
    else
    if( pctg == worst_pctg )
    worst += ", " + team;
    floser.printf( "%10s %2d %2d %5.3f\n", team, wins, losses, pctg );
    loser_count++;
    fin.close( );
    floser.close( );
    fwinner.close( );
    catch( IOException e ) {
    System.out.printf( "I/O error: %s\n", e.toString() );
    System.exit( 1 );
    System.out.printf( "%d teams have winning records; %d teams have losing records\n", winner_count, loser_count );
    System.out.printf( "Team(s) with best percentage: %5.3f %s\n", best_pctg, best );
    System.out.printf( "Team(s) with worst percentage: %5.3f %s\n", worst_pctg, worst );
    }

Maybe you are looking for

  • Ipod touch is frozen on apple logo & does not show up in itunes or computer

    My ipod touch 4G is frozen on th apple logo. I can't simply restore it because it doesn't show up in itunes (lastest) or in computer (I have vista). I tryd using the apple online troubleshooter but nothing works. Please help!

  • How do I change my name in Bonjour

    When using Bonjour in iMessage, my name is not showing up accurately.  When it is off and I am only using iCloud and AOL, my name is correct. But when I turn on Bonjour, the name changes to someone else. How can I correct this? Thank you.

  • Advance pricing Query

    No.     Price Range      ListPrice     No$al Price     Nett Price     Special Deal     Special Deal 2      Qty/Value Range     -     0 - 10pcs     11 - 99pcs     100 - 149pcs 150pcs & above No.1     ABC Part number     10.00      $10 - 10%     $10 -

  • HT4009 How do I get a refund for a recently purchased app that does not meet expectation?

    I purchased an application this weekend and it doesn't do what I was expecting it to do.  How do I return and be reimbursed for that application?

  • Mailboxes in another forest

    I'd like to ask what are my options on a scenario described here: Two AD forests without any trusts between (let's call em old and new) Old has users and Exchange 2000 New has the same users (with new samaccountnames) and Exchange 2013 There's no nee