If/else problem

Dear all
I have looked thru the NumberformatException stuff and still havent been able to get to the bottom of this one
here is my code - max and min are initially strings .
Ive been careful to test the equals to null first to avoid the null pointer exception but now i get a number format exception and cant see why. very grateful for any help thanks
//if max is not null and min is null
if (max != null && min == null) // this bit not working generates a NFE
int value = Integer.parseInt(max);
out.println("max generated");
//     this is working if min is not null and max is
else //(min!=null && max==null)
int value = Integer.parseInt(min);
out.println("min generated");

I tried it it works fine for me??
String max = "0";
String min = null;
if (max != null && min == null) // this bit not working generates a NFE
int value = Integer.parseInt(max);
System.out.println("max generated");
// this is working if min is not null and max is
else if(min!=null && max==null)
int value = Integer.parseInt(min);
System.out.println("min generated");

Similar Messages

  • Anyone else problems with Pentech Hotshot Phone

    Still can not get on line to check Weather Bug or my Verizion account, with old flip phone I had befor I could get to both no problem, nothing was to chang when I updated to a new phone.  Anyone else haveing problems?

    Yes it is 3G is enabled with 3 bars, also spent 2 hrs on phone with Verizon trying to figer out what is wrong, I have 2 phones on the same account and the other phone does the same can not connect error 403 no access.  Got both phones at the same time hard to beleave that both phones would be bad.

  • Anyone has else problems with the new earpods consistantly sliping out of the ear?

    just got the new iphone 5 and was listening to music while jogging, and the ear pods kept slipping off!! Its so annoying!! Atleast the older gen earphones did not slip off! So much for engineered fit!!

    Without proper system information nobody can tell you anything. there could be any number of reasons why the download gets corrupted from virus scanners accessing the files and damaging them to your harddrive being damaged or fragmented to a bad network connection already corrupting it... Check al lthat stuff, turn off the pertinent components, clean up your drive.
    Keeping your Harddrive in Shape
    Mylenium

  • Is netflix giving anybody else problems for the ipad 2?

    I installed the Netflix app onto my iPad and when I run it, log in, and try to play a movie/show it just goes back to the video selection screen.

    try going to the home page
    double click the home button
    press and hold the netflix icon till it wiggles
    tap the red circle
    now press the home button, then press it again
    now try launching netflix again

  • Connected Combo box problem !   please help me

    Dear Friends....!
    I am developing project in which i have 3 combo :
    1) District Selection
    2) Taluka Selection
    3) Village Selection
    Depend on village selection , perticular persons on that village is displayed on the page.
    This values must be fetched from DATABASE !
    <b> I tried with JAVASCRIPT but with it i can connect two combo and
    can't access database inside javascript. WHAT IS THE SOLUTION EXCEPT AJAX ( That i don't KNOW ) </b>
    may be i can put 3 combo together and on first OnChange event
    i can submit page and process another page and put values in
    another combo and forward page to combo page again.
    i am very much confused HELP ME !
    please i don't know AJAX else problem would be easily solved.
    EVEN I CAN"T MANUALLY PUT DATA IN JAVASCRIPT bcoz my villages
    are more than 400.
    how to put java database code in javascript OnChange event ???
    to fetch data of another combo ?
    HELP WITH EASY SOLUTION.
    Thanks
    GHanshyam
    ================================
    SOLUTION FOR TWO COMBO
    function populate(o) {
      d=document.getElementById('de');
      if(!d){return;}                
      var mitems=new Array();
      mitems['Choose']=[''];
      mitems['Salads']=['Select Item','Tuna Salad','Cesar Salad','Green Salad','Prawn Salad'];
      mitems['Main Courses']=['Select Item','Filet Mignon','Porterhouse','Flank','T-Bone'];
      mitems['Drinks']=['Select Item','Milkshake','Soda','Mixed Drink','Juice'];
      mitems['Desserts']=['Select Item','Ice Cream','Fresh Fruit','Pie'];
      mitems['Snacks']=['Select Item','Brownies','Cookies','Potato Chips'];
      d.options.length=0;
      cur=mitems[o.options[o.selectedIndex].value];
      if(!cur){return;}
      d.options.length=cur.length;
      for(var i=0;i<cur.length;i++) {
        d.options.text=cur[i];
    d.options[i].value=cur[i];
    <!-- Paste this code into the HEAD section of your HTML document.
    You may need to change the path of the file. -->
    <script type="text/javascript" src="dropdownBox.js"></script>
    <!-- Paste this code into the BODY section of your HTML document -->
    <form action="" method="get">
    <label for="or">Our menu:</label>
    <select name="or" id="or" onchange="populate(this)">
    <option value="Choose">Select from the Menu</option>
    <option value="Salads">Salads</option>
    <option value="Main Courses">Main Courses</option>
    <option value="Drinks">Drinks</option>
    <option value="Deserts">Deserts</option>
    <option value="Snacks">Snacks</option>
    </select>
    <label for="de">Select:</label>
    <select name="de" id="de"></select>
    <input type="submit" value="Show me" />
    </form>
    <p><div align="center">
    </div><p>

    may be i can put 3 combo together and on first
    OnChange event
    i can submit page and process another page and put
    values in
    another combo and forward page to combo page again.Almost there. What you should do is submit the page on the onChange event of the combo box; but submit to the same JSP. Then, depending on the values that each of the combo boxes contains, run a query for villages in that District and under that Talluka.
    And populate the third combo box. If any one of the ( first two ) boxes is empty i.e user didnt' select a value, then you'll automatically get no value for the combo boxes from the query.
    Something like this
    <%
        String selectedDistrict = request.getParameter("districtcombobox");
        String selectedTalluka = request.getParameter("tallukacombobox");
        //make sure you don't nulls
        selectedDistrict = selectedDistrict == null?"":selectedDistrict;
        selectedTalluka = selectedTalluka == null?"":selectedTalluka;
        PreparedStatement psFetchTallukas = con.prepareStatement("select tallukaname from tallukas where tallukadistrict = ?");
        PreparedStatement psFetchVillages = con.prepareStatement("select villagename from villages where villagetaluka = ?");
         psFetchTallukas.setString(1, selectedDistrict);
         psFetchVillages.setString(1, selectedTalluka);
       rsTallukas = psFetchTallukas.executeQuery();
       rsVillages = psFetchVillages.executeQuery();
    //now, print out your <option> elements under the corresponding <select> tags for each of the 3 select boxes
    %>For your onChange event you don't need to do anything except call form.submit() where the action should be the same JSP. In case your form is going to be submitted to another page on the final submit i.e after selecting all required values; then in the onChange event handler, before the submit(), you should change the action property of the form to the same page and then submit.

  • Weird problem with calls

    Hi, im using skype for windows 7 for about 2 years now...and never had a problem...since i formated my pc that's what happens:
     Only when I make a call (not when others invite me to their call) and everything seems to work fine...i get a message that tells me to wait until skype reestablish the conection ( i do NOT get disconected...at least that's what i see in my screen...and i thought it was somebody's else problem)...when the call is repaired the others tell me i disconected for a bit...even though my skype shows nothing like that...
     I have not changed anything in it's default settings since i installed it...but i checked my firewall and skype has an exception..that happens only when i make the call...if im invited to a call made by someone else...everything is fine... one last clue if it helps...i saw a quick message once that said my connection is very fast for this call or something like that...it disappeared quickly but i'm prety sure i red it right...+ my internet works fine... any help ??

    have you tried resetting your phone and then try?
    Reset your phone by pressing and holding the home button and the sleep button at the same time until you see a silver apple. Dont slide bar to turn off. Just keep pressing those two buttons until the apple appears.
    Message was edited by: Dynamite DJs

  • Audio Synch Problem Exporting From imovie 6

    I have a created a large imovie project in imovie 6 using pictures and imported video.  The project uses a lot of extracted audio voice overs on top of the photos. 
    While trying to export the video to quicktime or idvd, the audio gets out of synch at various points.  I have tried exporting it many times using a variety of different options, and the audio remains out of synch, sometimes in different places with each export.  Lastly, I have extracted the audio from the video clips for some of the more problematic portions of the project, but that has not proven successful.
    The odd thing is that the movie plays perfectly while in imovie.
    Any suggestions as to how to correct this issue?

    Hi
    Tedious situation.
    To avoid this I'm kind of strict in Audio in two ways
    A
    • Material used if video is in same frame per minute - else I use JES_Deinterlacer to convert all to one standard. I use PAL = 25fps - one of my Cameras records ONLY in 30fps - (some people records in 24fps - to get a movie feel - I never)
    So keeping the fps from Camera to (in my cases) DVD - gives a supperior result
    B
    • I'm strict in the kind of Audio formats I use - ONLY .aiff (or from miniDV tape Cameras) AND THEN 16-bit 48kHz or from Audio-CD (still .aiff as on normal CDs) and here 44.1kHz
    If Camera is set to record in LP-mode or 12-bit Audio - Then I use an external Audio Editor to get this right
    If from iTunes - I never use this directly - BUT - collect needed audio into a New PlayList - BURN THIS as a Standard Audio-CD (NO .mp3 - but .aiff here too) and then use the files on this CD in my movie project's in iMovie HD6 or FinalCut any varsion (or if forced to - iMovie'11)
    Else read this
    Audio Sync problems
    • 12.bit - should be 16.-bit (from miniDV tape - set Camera right)
    Avoid recording in LP-mode on miniDV tape. This tape must be play-backed by same Camera. When Camera dies
    so does the video material in worst case.
    • .mp3, .avi etc strange file formats - should be converted to .aiff 48kHz 16-bit
    • in iMovie (up to HD6) - do - Extract Audio - it most often helps
    • from iTunes - collect into a PlayList then Export out as an Audio-CD (not .mp3) and use the files on this (.aiff 44.1kHz)
    • There seems to be a problem with slow-down resp speed-up. Has to be in specific steps as 25% 50% 150% 200%
    else problems will arise
    • Audio problems when transitions is in use - especially iMovie HD/HD6
    a. Select video clips
    b. Extract Audio (Advance menu/Extract Audio)
    c. Now apply transition
    d. eventually fine-tune end and start of extracted audio clips
    Yours Bengt W

  • X200 Windows7 Battery Life Problem

    Hi, I have an X200 and recently installed Windows7 beta 7000 32bit. Even after getting all devices to work and installing Lenovo drivers where possible,  my battery life time never got better than about 60% of the batterylife time I had on vista.
    6 cell battery
    - around 6hrs on vista
    - less than 4hrs on Win7
    Today I installed Windows7 Build 7057 64bit and after installing all the drivers, all devices are working properly, but still the same really bad battery life!
    By now I really got used to Win7 user interface and improvements, I never want to switch back..... has anyone else problems like that? Any suggestions?
    Thanks,
    senorm

    I've got an x200. I interchange two drives in it, one personal and one for work. Both are Win7 64. One is upgraded from Vista Ultimate, one is a clean install. The battery is a 9 cell, and performs about the same on both. I'm using the Lenovo Power Management on both.
    I've not noticed a significant drop off of power, but what it's not perfect. Whenever the machine goes to sleep, whatever power management settings are in effect are frozen after that, until I reboot the machine. I thn again have control of the power settings until the machine again sleeps.
    For example, I like running on power saver. On a clean start, with power connected, the screen is bright, and the processor is running at a higher rate. If I sleep the machine and disconnect from power, went it reawakens, it behaves as if it is still connected to power - it does not drop to the battery settings.
    If I reboot at that point, then I have control of the power settings again, and the machine is on battery seetings (assuming I did not reconnect the power.) Everything functions as expected until the machine sleeps.
    Given that Windows 7 is beta, and Lenovo's drivers aren't optimized for Windows 7, I'm very pleased that battery power works as well as it does. I've whined in this forum that Lenovo should be providing beta power management drivers, but the reality is at this point things work farily well.
    I recommend patience and tweaking
    I'm looking forward to the Win 7 RC, hopefully we'll see more Lenovo drivers then. 
    x200 7454-CTO; 320GB HD; 4GB; Win 7 64bit - Now on RTM.
    - 2nd SSD with Win 7 Enterprise RTM
    T61p - RTM - Win 7 Enterprise
    S10 4231 for my wife - now on Win 7 Ultimate RTM

  • Problem after iOS5 with pairing iPhone with Car

    I have a Lexus is250 which paired beautifully with my iPhone and I was able to play music from phone in my car.  Since the upgrade, I cannot.  I have "repaired" "Blue tooth audio", the radio in car "looks" like it is playing (you can use the controls on the car stereo to forward through playlist and it forwards on phone" but no sound comes out.  This worked perfectly fine before iOS.  Any ideas?  I've deleted and re-paired phone twice....

    Same problem here with a 2011 Subaru Outback/Harman Kardon sound system. My iPhone 3GS used to work very well and auto-connect with the Harman Kardon system under iOS 4, but after upgrading to iOS 5 the iPhone looses connectivity each time I power the iPhone off and back on. It will keep connectivity as long as I do not do this. Turning the car off and back on works fine, connectivity re-establishes immediately. I even reset my iPhone and re-installed firmware and everything else - problem persists. SHAME ON APPLE FOR LOOSING CORE FUNCTIONALITY IN FAVOR OF BRINGING IN LOTS OF GIMMICS THAT ARE OF LITTLE OR NO USE IN EVERYDAY LIFE. SHAME ON APPLE ALSO FOR NOT PROPERLY BETA-TESTING THEIR SOFTWARE AND MAINTAINING BACKWARD-COMPATIBILITY IF THAT IS THE PROBLEM. We users should be entilted to monetary compensation from Apple whenever a software "upgrade" negatively affects a core functionality. Tim Cook, please correct some of the flawed corporate policies the belated Steve Jobs implemented. Apple still has a lot of room for improving! First of all, focus on optimizing core functionalities and their robustness before wasting time on changing icons or other cosmetic features.

  • Hp officejet 4620 series doesnt display on my windows 8.1 to connect to scan

    This is a new printer purchased in 2014 hp officejet 4620 series doesn't display on my windows 8.1 to connect to scan.It does detect in HP AIO Remote app in windows 8.1 as seen on left but when i click on scan there it open hp scan and capture app and says unable to contact device as shown on right. I do restart my printer and PC at those times but sometimes also restart my wireless router. my internet has high speed  of 115Mbps with Comcast. There is no problem with the internet provider problem should be with the printer it doesn't show up wirelessly in the laptop or else problem should be with the hp scan and capture app for not detecting the printer either way i didn't get any solution. This is always the same problem i face daily. Someone please do help in solving this its so frustrating when the device doesn't get detected to print and scan.

    Hi @reshmi,
    Welcome to the HP Forums!
    I am sorry to hear about your frustration you are having with your HP Officejet 4620 not being able to scan on Windows 8.1. But I am happy to help you with this issue!
    Are you able to make copies with your printer? (This way we know the hardware is functioning properly.)
    I would recommend the following guides:
    A 'No Computer Detected' or 'Connection Error' Message Displays When Scanning for HP Officejet 4610 ....
    Printer Does Not Maintain Wireless Connection. 
    (Even though the guide titles may not match your issue, I believe the solutions will help.)
    To verify if this is an issue with your HP Scan and Capture app, please try one of the alternate methods of scanning in this how to scan guide, Scan from Windows 8 With the Full Feature HP Software for HP Multifunction Printers. Select How to scan without HP software, and let me know if one of those methods work for scanning or not.
    Thank you for posting, and have a good day!
    RnRMusicMan
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos Thumbs Up" to say “Thanks” for helping!

  • File Server Slowdown with Illustrator(only) saving and opening

    Hello,
    I have a problem i have been struggling with for years.
    When we save a file to the server, the time to open, save or export can be anywhere from 1-5 minutes. Its killing our productivity.
    I have changed out every component. We have Eight illustrator CS3 13.0.2 users on C2D/i3/i7 iMacs running 10.6.7. They are connecting to a Mac 10.6.7 Server with AFP - mac mini 2.53 with a lacie 5 drive raid.
    We have had this problem going back to at least 10.4.6 i think it was.  (I did not write good troubleshooting logs back then)
    What appears to be happening:
    open a file in the finder or in illustrator
    if a font is missing, it immedialy pings you, so its like illustrator looks at the files and then is looking for something else  (problem exists if no fonts are present)
    the mouse then beach balls and illustrator shows as not responsive
    the server shows some activity on the cpu/network/hard drive side but its very minor. like a get info command on lots of files
    local user shows very little to no activity
    then it stops doing nothing after the few minutes and it opens quickly.
    the content of the files does not effect the problem. A 10 meg files with lots of stuff takes maybe 4 minutes vs 3 min 50 seconds for a empty file
    my solution so far:
    I can clear the problem by running a script that deletes the illustrator prefs, mediabrowser.plist, deletes illustrator cache files, deletes apple quarantie events, bridge prefs. and a restart. Then files open in under 5 seconds. After a couple of hours or some times a day, the open times creep up to a minute, after a few days, they are 2-5 minutes.  Sometime clearing these files does not work and i have to then wipe a machine and do clean installs of everything.  Some Macs will not have the problem, and function great for a month and then they have the problem for no explainable reason.
    All other functions work great, no problems anywhere with anything else, excempt saving illustrator files to the server.
    We have tried moving the files locally and then copying them back, but we loose too much work with the errors associated with version control problems. Also a synced folder to the local machines of the server (yes that was intense on the machines) some how had the problem follow it on some macs but not others
    I have tried illustrator CS4 and CS5 and it has the same problem
    I am currently trying to brute force attack the problem, I figure i can reduce the wait time to maybe 20% with a Mac pro and a bank of SSD's. my cost is almost 8k. I am not happy giving up on fixing the bug, but we have at least 1-2 people waiting around at any given time. 
    Any thoughts on the problem or a solution?

    To create a new Swatches panel to store pattern swatches you have to:
    a) Open the Swatches panel and delete all the swatches that you don't want (optional)
    b) Choose Save Swatch Library as AI (not ASE) from the Swatches panel menu (I suggest you to save it on the Desktop! So you can easily find that!).
    The saved file is actually a simple (blank) Illustrator file.
    To use this file with other Illustrator projects choose Window > Swatch Library > Other Libraries and navigate to the saved Illustrator file (Desktop).
    At this point another swatches panel is opened on the screen.
    Drag the desired swatches from this new  panel to the document one. Then close the new panel.
    I hope this help

  • ITunes 6.0.3 and Airport Express 6.3: incompatible?

    I had several problems with sound dropouts in multiple speakers setup (see related posts as many other had same problem).
    The only way to circumvent the problem was to use a WIRED ethernet connection between the iMac and the AX, used in client mode.
    Now I upgraded iTunes to 6.0.3 and I get a message that 'your remote speakers are not compatible with this version of iTunes' , and the remote speakers are not even visible in the iTunes bottom bar.
    However, if I connect in WIRELESS mode, using the AX as wireless access point, I see the remote speakers, BUT I get again the audio dropouts.
    Has anyone else problems in connecting in wired ethernet to the AX with the 6.0.3 iTunes?
    What is going on, is it not possible to have a decent multiple speakers setup, wireless or wired? I am really tempted to return the AX, it is really disappointing.
    Thanks in advance for help

    I don't feel qualified to answer your specific question but I can say with certainty that you can run iTunes 6.03 with an AEx V6.3
    I am running an AExtreme as a main base (V5.7) allowing WDS and two AExpress (V6.3) as remote bases allowing WDS and both allowing wireless client connections. The network is WPA2 Presonal encrypted. I have iTunes V6.03.
    The first AX is about 12 feet from the base and the second is about 45 feet from the first. I can select mutiple speakers and stream music from iTunes (even using Live 365 as my stream source through Tunes) and I have had no drops and the music has been perfectly synced. I have even used one of the Macs to stream to one set of speakers and used the PC laptop to stream to the other set.
    I will admit to spending about four hours re-setting and re-configuring the AX's settings before I came up with the above combination. I spent a fair amount of time in the airport setup assistant but the finished product does what I wanted it to do. As a bonus, I got more wireless reach for the laptop.
    2 iMacs, 3 iPods, APBS, 2AEs   Mac OS X (10.4.5)   Laptop PC w/iTunes on network with the iMacs
    2 iMacs, 3 iPods, APBS, 2AEs   Mac OS X (10.4.5)   Laptop PC w/iTunes on network with the iMacs

  • Aperture STILL won't launch

    Aperture stopped launching this morning. I tried the fix suggested in another thread of replacing the Prokit.framework with an older version but it didn't work for me. Unfortunatley that discussion is marked as answered and has gone off in another direction.
    Running version 1.5.6 of Aperture.
    Odly another minor app won't work, You Control Tunes. Don't know if there's any connection. But right now I need to get Aperture up and running as I have photos to deliver tomorrow.

    I think I found the problem, you may not believe me though.
    I got Aperture working again after reinstalling Pro App Support even though it didn't work the first time. The one that worked for me is the latest version which seems to be causing everyone else problems. Anyway suddenly today Aperture stopped working again. Annoying beyond belief. So I reinstalled Pro App Support again and it worked again.
    But here's the weird thing – just before both Aperture crashes I remembered doing the same thing on my computer. This may sound weird but both crashes (or refusal to launch) happened just after I connected my Nokia 6300 via bluetooth (USB d-link connector) to my Mac. Now I know what you're thinking, how on earth could that have anything to do with Aperture? I agree. Whether it's just some bizarre coincidence or some unknown technical flaw the fact is that it's the only thing I did with my computer. Anybody out there know why bluetooth might affect Pro App Support?

  • XI java mapping using SAX

    Hi,
    im using java mapping for complex IDOC structure. If I run program localy, it works great, but when XI runs mapping, I have problems with xml file, some elements are not there ?! I don't know why it happens.....i said that i'm using complex logic, and therefore I'm using complex IF statments to produce segment in IDOC. I have noticed that there is a problem, because when I switch off IF, everything is fine???? any idea??
    thx mario

    Hi,
    Do you have nested 'if' statements?  Is it possible you could be experiencing a "dangling else" problem?
    http://www.dai-arc.polito.it/dai-arc/manual/tools/jcat/main/node101.html

  • Swing/JScrollPane

    My problem is that I have this class that extends JApplet and has 3 JPanel and an instance from another class that extends JPanel (I will call it class2) inside it.
    My problem is that I'm inserting class2 inside a JScrollPane than I insert JScrollPane inside my JApplet, but whenever I move my JScrollPane which should just move the content from class2 (lines, numbers, ...), but I'm getting a messed screen like if the computer was mixing the old content (before using JScrollPane) with the new content (after moving)...something like the JScrollPane listener isnt refreshing the screen when I use it.
    If anyone know a fix for this, please contact me and if you want to check the code, email me ([email protected]).

    I'm posting all the code below...could anyone please help me out with this, there is a very weird behaviour when I move the JScrollPane
    * C�digo de Huffman - Applet
    * Arildo Fran�a Oliva Filho - 99/32810
    * Leonardo Lobo Pulcineli - 99/20064
    * Marcos Garrison Dytz - 99/20102
    * Octavio do Vale Rocha - 99/20129
    package huffman;
    // Bibliotecas que fazem parte da implementa��o do applet
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    import java.text.DecimalFormat;
    * Objetos que far�o parte da GUI do programa, onde se tem a ocorrencia de
    * tres botoes para o controle do fluxo do programa, uma caixa para a entrada
    * das probabilidades, um classe instanciada para controlar as mensagens ao
    * usu�rio e outra que far� a apresenta��o de todo conte�do
    * Declara��o de todas as vari�veis utilizadas para armazenar as probabilidades
    * onde o maior n�mero de vari�ives que podem ser implementadas � 200
    public class Huff extends JApplet implements ActionListener, ComponentListener {
    JButton reset_button, step_button, end_button;
    // JButton file_button, fix_button;
    JTextField input_string;
    cent Cent = new cent();
    ErrorCanvas stdout = new ErrorCanvas();
    DecimalFormat f = new DecimalFormat("0.000"); // Define um formato para os valores
    DecimalFormat f2 = new DecimalFormat("0.00");
    JScrollPane scroll = new JScrollPane(Cent);
    boolean inAnApplet = true; // Testa a validade do applet
    protected int numProbabilidade; // Numero total de probabilidades
    protected int numProbabilidadeTemp; // Numero total de probabilidades
    protected int[] marcador; // Marca a pr�xima probabilidade
    protected double[][] probabilidade;
    protected String[][] simbolo; // Guarda os c�digos bin�rios
    protected int passo; // Controle quanto ao fim das probs.
    protected boolean proximo = true; // Idem acima
    protected double entropia = 0.0; // Entropia;
    // protected boolean estArquivo = true; // Estado de um arquivo
    protected boolean inic = true;
    * Construtor para a classe Huff (inicializa todo o GUI)
    public Huff() {
    getContentPane().setLayout(new BorderLayout());
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    getContentPane().add("Center", scroll);
    Font def = new Font("Dialog", 0, 12);
    Cent.setFont(def);
    JPanel p = new JPanel(new GridLayout(2, 0));
    JPanel q = new JPanel(new GridLayout(2, 0));
    JPanel r = new JPanel(new FlowLayout());
    r.add(reset_button = new JButton("Reiniciar"));
    r.add(step_button = new JButton("Proximo"));
    r.add(end_button = new JButton("Concluir"));
    // r.add(file_button = new JButton("Arquivo");
    // r.add(file_button = new JButton("Corrigir arquivo");
    p.add(r);
    p.add(input_string = new JTextField());
    * O visualizador gr�fico (JPanel q) que � utilizado por ErrorCanvas para
    * emitir algumas mensagens para o usu�rio
    q.add(p);
    q.add(stdout);
    getContentPane().add("South", q);
    reset_button.addActionListener(this);
    step_button.addActionListener(this);
    end_button.addActionListener(this);
    input_string.addActionListener(this);
    scroll.addComponentListener(this);
    * M�todo utilizado para inicializar o �ndice dos arrays utilizados e zerar
    * o valor de todas as probabilidades utilizadas
    public void init() {
    marcador = new int[200];
    probabilidade = new double[200][400];
    simbolo = new String[200][250];
    for(int i = 0; i < 200; i++)
    for(int j = 0; j < 400; j++) {
    probabilidade[i][j]=0.0;
    JOptionPane.showMessageDialog(null, " ", "Bem vindo",
    JOptionPane.INFORMATION_MESSAGE);
    if(inic)
    iniciarProbabilidade(probabilidade[0]);
    this.reset();
    * Conta o n�mero de probabilidades que foram inseridos no TextField, assim
    * como testa a validade destes valores. � bem similar ao funcionamento de
    * parseProbabilidade
    void contarProbabilidade() {
    StringTokenizer st = new StringTokenizer(input_string.getText());
    double teste = 0.0;
    if(input_string.getText().length() > 0 && input_string.getText() != null) {
    while (st.hasMoreTokens()) {
    try {
    teste = Double.valueOf(st.nextToken()).doubleValue();
    if(teste < 0) {
    JOptionPane.showMessageDialog(null,"Probabilidade negativa.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    if(teste > 1.0) {
    JOptionPane.showMessageDialog(null,"Probabilidade maior que 1.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    if(teste == 0.0) {
    JOptionPane.showMessageDialog(null,"Probabilidade igual a 0.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null,"Numero incorreto.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    numProbabilidade++;
    if(numProbabilidade > 200 && st.hasMoreTokens()) {
    JOptionPane.showMessageDialog(null,"S�o permitidos at� 200 probabilidades",
    "Erro", JOptionPane.ERROR_MESSAGE);
    input_string.setText("");
    numProbabilidade = 0;
    break;
    } else
    JOptionPane.showMessageDialog(null,"Insira algum valor.",
    "Erro", JOptionPane.ERROR_MESSAGE);
    * Todos os m�todos abaixos far�o algum ajuste necess�rio quando ocorrer uma
    * mudan�a no ScrollPane
    public void componentResized(ComponentEvent e)
    scroll.getSize();
    public void componentMoved(ComponentEvent e)
    public void componentShown(ComponentEvent e)
    public void componentHidden(ComponentEvent e)
    * Listener utilizado por Java para fazer todo o controle dos Eventos que
    * ocorram no aplicativo, ou seja, o pressionar dos tr�s bot�es, assim como
    * a utiliza��o da tecla Enter dentro do TextField. Para cada uma destas
    * a��es se encontrar� um c�digo diferente para seu processamento correto
    public void actionPerformed(ActionEvent evt) {
    if(evt.getSource() == reset_button) {               // Bot�o de Reiniciar
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText()))
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    * O bot�o de Proximo pode ser visto abaixo e ele quem far� todo o controle
    * gr�fico, assim como matem�tico em rela��o aos pr�ximos valores a serem
    * impressos na tela utilizando diversos m�todo diferentes
    } else if(evt.getSource() == step_button) {
    if(proximo) {
    if(calcProbabilidade(passo)) {
    proximo = false;
    marcador[passo] = -1;
    passo--;
    } else {
    int tmp = 0;
    for(; tmp < 400; tmp++)
    if(probabilidade[passo-1][tmp] == 0.0)
    break;
    Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
    stdout.println("As duas probabilidades inferiores da coluna " + passo
    +" foram somadas: " +
    f.format(probabilidade[passo-1][tmp-1]) + " + " +
    f.format(probabilidade[passo-1][tmp-2]) + " = " +
    f.format(probabilidade[passo][marcador[passo]]), false);
    stdout.println(1, "A soma � mostrada em negrito na coluna 2.",false);
    passo++;
    if(!proximo) {
    if(passo < 0) {
    Cent.setReverseStep(-1,-1,-1);
    end_button.setEnabled(false);
    step_button.setEnabled(false);
    for(int k = 0; k < 200; k++) // C�lculo da entropia
    if (probabilidade[0][k] != 0)
    entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
    Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
    Double ent = new Double(entropia);
    entropia = 0;
    String cod = new String("Codigo correspondente:\n\n");
    for(int m = 0; m < 200; m++)
    if (simbolo[0][m].length() > 0)
    cod += simbolo[0][m] + "\n";
    JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
    stdout.println("Num. Prob.: " + numProbabilidade +
    " Entropia: " + ent);
    } else {
    designaSimbolo(passo);
    Cent.printReverseStep(passo,simbolo[passo]);
    passo--;
    * O bot�o de Concluir e ele simplesmente executar� o mesmo c�digo do bot�o
    * Proximo, por�m at� o fim da execu��o do programa *
    } else if(evt.getSource() == end_button) {
    end_button.setEnabled(false);
    step_button.setEnabled(false);
    entropia = 0;
    for(int k = 0; k < 400; k++) {
    if(proximo) {
    if(calcProbabilidade(passo)) {
    proximo = false;
    marcador[passo] = -1;
    passo--;
    } else {
    int tmp = 0;
    for(; tmp < 400; tmp++)
    if(probabilidade[passo-1][tmp] == 0.0)
    break;
    Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
    passo++;
    if(!proximo) {
    if(passo < 0) {
    Cent.setReverseStep(-1,-1,-1);
    } else {
    designaSimbolo(passo);
    Cent.printReverseStep(passo,simbolo[passo]);
    passo--;
    } // C�lculo da entropia abaixo
    if (probabilidade[0][k] != 0)
    entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
    Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
    Double ent = new Double(entropia);
    entropia = 0;
    stdout.println("Entropia " + f.format(ent));
    String cod = new String("Codigo correspondente:\n\n");
    for(int m = 0; m < 200; m++)
    if (simbolo[0][m].length() > 0)
    cod += simbolo[0][m] + "\n";
    JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
    stdout.println("Num. Prob.: " + numProbabilidade +
    " Entropia: " + ent);
    * O c�digo abaixo far� todo o papel de abrir um arquivo com probabilidades,
    * assim como salvar um arquivo com as probabilidades
    /* } else if(evt.getSource() == file_button) {
    if(estArquivo) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY):
    fileChooser.showSaveDialog(this);
    File fileName = fileChooser.getSelectedFile();
    if (fileName == null || fileName.getName().equals(""))
    JOptionPane.showMessageDialog(null, "Arquivo inv�lido.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    else {
    try {
    ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileName));
    String arq = (String) input.readObject();
    input_string.setText(arq);
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText())) {
    estArquuivo = false;
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    } catch (EOFException e) {
    JOptionPane.showMessageDialog(null, "Erro de EOF.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException e) {
    JOptionPane.showMessageDialog(null, "Erro: Class Not Found.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao abrir arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    try {
    input.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } else {
    if (passos < 0) {
    try {
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("c:\codigo.txt"));
    for(int o = 0; o < 200; o++) {
    while(simbolo[0][o].length() != 0) {
    output.writeObject(simbolo[0][o])
    output.writeObject(" ");
    output.flush();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao salvar no arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    try {
    output.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    } else {
    JOptionPane.showMessageDialog(null, "Finalize o processo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    /* } else if(evt.getSource() == fix_button) {
    try {
    input.close();
    estArquivo = true;
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "Erro abrindo arquivo.", "Erro",
    JOptionPane.ERROR_MESSAGE);
    * A a��o que ocorre quando se pressiona o bot�o Enter dentro do TextField
    * pode ser vista abaixo e � bem similar ao pressionar do bot�o Reiniciar
    } else if(evt.getSource() == input_string) {        // Utiliza��o da TextBox
    end_button.setEnabled(true);
    step_button.setEnabled(true);
    numProbabilidade = 0;
    contarProbabilidade();
    if(input_string.getText().length() > 0) {
    if(parseProbabilidade(input_string.getText()))
    this.reset();
    stdout.println("Applet reinicializado");
    this.reset();
    } else {                                            // Problema!
    stdout.println("Evento desconhecido ");
    * M�todo utilizado quando o bot�o Reiniciar � pressionado, ele reinicia os
    * valores para todas vari�veis e coloca na primeira coluna os primeiros
    * valores utilizados na �ltima experimenta��o
    void reset() {
    int i = 0, j = 0;
    Cent.clearScreen(probabilidade[0]);
    proximo = true;
    passo = 1;
    for(i = 0; i < 200; i++)
    marcador[i] = -1;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 250; j++)
    simbolo[i][j] = "";
    * Testa quanto a viabilidade das probabilidades inseridas no TextBox estarem
    * de acordo com os criterios adotados e � bem simples de ser compreendida
    boolean parseProbabilidade(String s) {
    int linha = 0, i = 0;
    double soma = 0.0;
    double[] d = new double[200];
    StringTokenizer st = new StringTokenizer(s); // Conta o n�mero de itens
    // dentro de input_string
    for(i = 0; i < 200; i++)
    d[i] = 0.0;
    i = 0;
    while (st.hasMoreTokens()) {                  // Testa se h� mais Tokens
    try {
    d[i] = Double.valueOf(st.nextToken()).doubleValue();
    if(d[i] < 0) {
    return(false);
    if(d[i] > 1.0) {
    return(false);
    if(d[i] == 0.0) {
    return(false);
    } catch (NumberFormatException e) {
    JOptionPane.showMessageDialog(null, "Os n�meros n�o estao em sua forma correta",
    "Erro", JOptionPane.ERROR_MESSAGE);
    return(false);
    i++;
    bubblesort(d);
    for(i = 0; i < 200; i++) {                  // Testa quanto a viabilidade da
    soma += d; // das vari�veis
    if((soma <= 0.999999) || (soma >= 1.000001)) {
    JOptionPane.showMessageDialog(null, "A soma das probabilidadades n�o e igual a 1." +
    "\nA soma das probabilidade foi " + soma, "Erro", JOptionPane.ERROR_MESSAGE);
    return(false);
    for(i = 0; i < 200; i++)
    probabilidade[0][i] = d[i];
    stdout.println("Entrada de probabilidades correta. Pressione " + '\"' +
    "Proximo" + '\"' + " para continuar.");
    return(true);
    * Este m�todo ser� utilizado como sentinela pra a inicializa��o das
    * probabilidades
    void iniciarProbabilidade(double[] p) {
    inic = false;
    iniciarProbabilidade(p, p.length-1);
    * Executa a inicializa��o para alguns valores das probabilidades a partir
    * do objeto Rand()
    void iniciarProbabilidade(double[] p, int n) {
    Random rand = new Random();
    double soma = 0.0, s = 0.0;
    int i = 0;
    String input = " ";
    stdout.println(null); // Limpa o texto abaixo
    for(; i < 20; i++) {
    p[i] = rand.nextDouble() + 0.1; // Gera os n�meros iniciais
    soma += p[i]; // onde se deseja valores pr�ximos
    for(i = 0; i < 20; i++) {
    p[i] /= soma; // Escalonamento
    p[i] = Math.floor(p[i]*100) / 100.0; // Truncamento
    s += p[i];
    for(i = 0; i < 20; i++) // Utilizado para equilibrar as
    if(p[i] < 0.001) {                      //  probabilidades
    p[i] += 0.01;
    s -= 0.01;
    if (s < 1.000) {                          // Utilizado para inteirar a soma
    double resto = 1.0 - s;
    p[0] += resto;
    bubblesort(p);
    for(int k = 0; k < 20; k++) // Constroi string a ser exibida
    input += f2.format(p[k]) + " "; // dentro de string_input
    String input2 = input.replace(',','.');
    input_string.setText(input2);
    contarProbabilidade();
    * Faz um sort bem comum de todos as probabilidades inseridas
    void bubblesort(double[] d) {
    for(int i = 0; i < (d.length - 1); i++)
    for(int j = 0; j < (d.length - 1); j++)
    if(d[j] < d[j+1]) {
    double t = d[j];
    d[j] = d[j+1];
    d[j+1] = t;
    * Calcula o valor da probabilidade resultante a partir da soma das duas
    * probabilidades anteriores e seu c�digo � representando somente por loops
    * que setam estes valores
    boolean calcProbabilidade(int passo) {
    int n = 0, i = 0;
    double soma = 0.0;
    if(passo >= 0) {
    for(; i < 400; i++)
    if(probabilidade[passo-1][i] == 0.0)
    break;
    n = i;
    soma = probabilidade[passo-1][n-1] + probabilidade[passo-1][n-2];
    for(i = 0; i < 200; i++)
    if(probabilidade[passo-1][i] >= soma) {
    probabilidade[passo][i] = probabilidade[passo-1][i];
    } else
    break;
    marcador[passo] = i;
    probabilidade[passo][i] = soma;
    for(; i < 200; i++)
    probabilidade[passo][i+1] = probabilidade[passo-1][i];
    probabilidade[passo][n-1] = 0.0;
    probabilidade[passo][n] = 0.0;
    if(n == 2)
    return(true);
    else
    return(false);
    return(true);
    * Designa todos os s�mbolos ou c�digos para as probabilidades inseridas
    * a partir do controle feito pelos m�todos "actionPerformed" e
    * "calcProbabilidade"
    void designaSimbolo(int passo) {
    int i = 0, m = marcador[passo+1];
    String str = "";
    if(m == -1) {
    simbolo[passo][0] = "0";
    simbolo[passo][1] = "1";
    stdout.println("Os primeiros valores (0 e 1) foram designados na coluna" +
    " da extrema direita.", false);
    } else {
    for(; i < 400; i++)
    if(probabilidade[passo+1][i] != 0.0) {
    if(m == i) {
    str = simbolo[passo+1][i];
    } else if(m < i) {
    simbolo[passo][i-1] = simbolo[passo+1][i];
    } else if(m > i) {
    simbolo[passo][i] = simbolo[passo+1][i];
    } else
    System.out.println("Problema!!!");
    } else
    break;
    Cent.setReverseStep(passo,i,m);
    stdout.println("O c�digo correspondente a probabilidade marcada (" +
    f.format(probabilidade[passo+1][m]) +
    ") foi usado como base para se designar os valores.", false);
    stdout.println(1,"O c�digo das duas probabilidade inferiores (" +
    f.format(probabilidade[passo][i-1]) + ")(" +
    f.format(probabilidade[passo][i]) + ")" +
    " foram modificados. Os outros c�digos permanecem" +
    " os mesmos.", false);
    simbolo[passo][i-1] = str + "0";
    simbolo[passo][i] = str + "1";
    * Inicializa todo o aplicativo caso seja feito stand-alone
    /* public static void main(String args[]) {
    JFrame f = new JFrame("C�digo de Huffman");
    Huff codigo = new Huff();
    codigo.inAnApplet = false;
    codigo.init();
    f.getContentPane().add("Center", codigo);
    f.setSize(800,600);
    f.show();
    codigo.start();
    * A classe abaixo � utilizada para o controle de todas as mensagens exibidas
    * ao usu�rio do applet a partir do JPanel stdout, assim como comunica��o
    * via interface MS-DOS
    class ErrorCanvas extends Canvas {
    private String output, output2;
    public void paint(Graphics g) {
    if(output == null) {
    g.drawString("C�digo de Huffman", 350, 20);
    g.drawString("Arildo Fran�a Oliva Filho - 99/32810", 20, 40);
    g.drawString("Leonardo Lobo Pulcineli - 99/20064", 20, 60);
    g.drawString("Marcos Garrison Dytz - 99/20102", 550, 40);
    g.drawString("Octavio do Vale Rocha - 99/20129", 550, 60);
    } else {
    g.drawString(output,20,20);
    void println(String s)
    println(0,s);
    void println(String s,boolean echo)
    println(0,s,echo);
    void println(int linha,String s)
    println(linha,s,true);
    void println(int linha,String s,boolean echo)
    if(linha == 0)
    output = s;
    output2 = "";
    } else
    output2 = s;
    this.repaint();
    if(s != null && echo)
    System.out.println(s);
    * A classe abaixo � utilizada na cria��o de toda a interface gr�fica utilizada
    * pelo programa como as diversas setas que ligam as probabilidades, a cria��o
    * das colunas e controle em rela��o as cores dos c�digos.
    * Grande parte do c�digo deste classe deve ser creditado a Paul Williams.
    class cent extends JPanel {
    private int reverse_step = -1;
    private int rs_y, rs_m;
    private String[][] buffer; // O conjunto de vari�veis abaixo controlam
    private int[] xoffsets; // todo o posicionamento dos diferentes
    private int[] yoffsets; // objetos na tela
    private int[] lines;
    private int yoffset,yhalfoffset,linexoffset,
    ybelowoffset,xrightoffset;
    protected boolean isinit = false;
    protected boolean repainting = false;
    Font boldfont = null, deffont;
    DecimalFormat f = new DecimalFormat("0.00");
    * Executa a inicializa��o de todas vari�veis e arrays, assim como dos objetos
    * que ser�o manipulados pela interface gr�fica caso eles n�o tenham ocorrido
    void init() {
    if(!isinit) {
    xoffsets = new int[200];
    for(int k =0; k < xoffsets.length; k++)
    xoffsets[k] = 40 + k * 60;
    yoffset = 16;
    yoffsets = new int[400];
    int i;
    for(i = 0; i < yoffsets.length; i++)
    yoffsets[i] = 30 * (i+1) + 60;
    buffer = new String[200][400];
    int j;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 400; j++)
    buffer[i][j] = "";
    lines = new int[400];
    for(i = 0; i < lines.length; i++)
    lines[i] = -1;
    linexoffset = 45; // offset of left of line from left of text
    xrightoffset = 5; // offset between forward and reverse(red) text
    ybelowoffset = 12; // offset between forward and reverse(red) text
    yhalfoffset = 5; // offset for lines (half a character)
    deffont = new Font("Dialog", 0, 12);
    boldfont = new Font("Dialog", Font.BOLD, 12);
    if(deffont == null || boldfont == null) {
    boldfont = null;
    System.out.println("N�o foi poss�vel indicar o valor para as fontes.");
    isinit = true;
    repainting = false;
    * Construtor para essa classe e define que se a classe n�o tive sido inicia-
    * lizada, ent�o ser� por este construtor
    public cent()
    if(!isinit)
    this.init();
    * Limpa todo o conte�do exibido no JPanel Cent
    void clearScreen(double[] p) {
    int i,j;
    for(i = 0; i < 200; i++)
    for(j = 0; j < 400; j++)
    buffer[i][j] = "";
    for(i = 0;i < lines.length; i++)
    lines[i] = -1;
    for(i = 0; i < 200; i++) {
    if(p[i] == 0.0)
    buffer[0][i*2] = "";
    else
    buffer[0][i*2] = f.format(p[i]);
    repaint();

Maybe you are looking for

  • How do I calculate days from two different dates?

    Hi all, How do I calculate days from two different dates? my requirement is to pass the number of days to target field from two dates. Current date :  14/04/2010 Standard date: 01/01/1957 is the standard = day 0 Is it possible in graphical mapping wi

  • What default font is being used for skin tooltips in captivate 6.0

    What default font is being used for skin tooltips in captivate 6.0

  • Increasing saturation/color in one area

    I have a photo , which is a close up, that i would like to increase the color or saturaion in just the blue of her eyes. the rest of the photo is fine the way it is. i would like her blue eyes to really pop off the page so to speak and i am not sure

  • HOW TO DO: J2EE declaritive Security without LDAP????

    My client doesn't want to store stuff in LDAP, and we already have existing authoriztion infrastruction stored in a DB. How can I my existing security infrastructure in conjuction with J2EE declarative security and iAS (6sp3, Solaris, oracle db, web

  • AAMEE 2.1 Doesn't Load

    I downloaded AAMEE 2.1 to configure a CS 5.5 deployment. I was able to get it configured and deployed no problem. I want to run it again to make a change to my deployment, but AAMEE does not load. No error message or anything. If I try to re-install