Program Will Not Terminate

The program isnt terminating because of the line
while(fileScan.hasNext()). There are 18 lines in the text file that is being scanned from but commandcount only allows 16 because of this line:
while(position < commandcount)
That is what I want to happen, only I want the prorgram to terminate after printing the 16 lines. Any suggestions. Its much appreciated.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class Calculator
    public static void main (String[] args) throws IOException
        final String filepath = "calculator.txt";
        int position = -1;
        int commandcount;
        int count = -1;
        double data;
        double x = 0;
        double answer = 0;
        String command, commandline, answerstring;
        DecimalFormat fmt = new DecimalFormat ("0.000");
        Scanner fileScan = new Scanner(new File(filepath));
        commandcount = fileScan.nextInt();
        fileScan.nextLine();
           while(fileScan.hasNext())
              while(position < commandcount)
              commandline = fileScan.nextLine();
              Scanner commandlineScan = new Scanner(commandline);
              command = commandlineScan.next();
              data = commandlineScan.nextDouble();
              if (command.equals("sin"))
                {data = Math.toRadians(data);
                answer = Math.sin(data);
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("cos"))
                {data = Math.toRadians(data);
                answer = Math.cos(data);
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("tan"))
                {data = Math.toRadians(data);
                answer = Math.tan(data);
                System.out.println(commandline + " = " + fmt.format(answer));}   
              else if (command.equals("sqrt"))
                {answer = Math.sqrt(data);
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("abs"))
                {answer = Math.abs(data);
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("n!"))
                 {for(x = data; data > 1; data--)
                    x *= data - 1;
                 answer = x;
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("inv"))
                {answer = 1/data;
                System.out.println(commandline + " = " + fmt.format(answer));}
              else if (command.equals("pow"))
                {while(commandlineScan.hasNext())
                  {double b = commandlineScan.nextDouble();
                  answer = Math.pow(data, b);
                  System.out.println(commandline + " = " + fmt.format(answer));
              else if (command.equals("min"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                  if (num < answer)
                    answer = num;
                System.out.println(commandline + " = " + fmt.format(answer));
              else if (command.equals("max"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                  if (num > answer)
                    answer = num;
                System.out.println(commandline + " = " + fmt.format(answer));
              else if (command.equals("+"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer += num;
                System.out.println(commandline + " = " + fmt.format(answer));   
              else if (command.equals("-"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer -= num;
                System.out.println(commandline + " = " + fmt.format(answer));   
              else if (command.equals("*"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer *= num;
                System.out.println(commandline + " = " + fmt.format(answer));   
              else if (command.equals("/"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer /= num;
                System.out.println(commandline + " = " + fmt.format(answer));   
              else if (command.equals("%"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer %= num;
                System.out.println(commandline + " = " + fmt.format(answer));   
              else if (command.equals("average"))
                {answer = data;
                while (commandlineScan.hasNext())
                  {double num = commandlineScan.nextDouble();
                   answer += num;
                   count++;
                answer /= count; 
                System.out.println(commandline + " = " + fmt.format(answer));   
               ++position;                     
}

After the inner while loop add:
if (position >= commandcount) {
  fileScan.close();
}Not necessaily the best fix, but at least a quick one.
Edit: Just remember to catch the IllegalStateException.
Or, to avoid the exception do (this time before the while loop rather than after, else if the file contains exactly as many lines as needed it will result in a different exception)
if (position >= commandcount) {
  fileScan.nextLine();
}

Similar Messages

  • The program will not close properly unless I turn off the computer.

    The program will not close properly. If I close it and then try to restart it I get a message saying that Firefox is already running.

    Even under normal circumstances it takes a few seconds after exiting Firefox before you can launch Firefox again successfully.
    But you're right, sometimes a zombie Firefox process lives on, consuming CPU cycles and memory long after all the user interface for it has disappeared. The zombie Firefox process blocks the launch of new ones. It's annoying, but there is a lighter-weight work-around than rebooting. If you key Del while holding down Ctrl and Alt (the old three-finger DOS reboot), either the Windows Task manager will pop up immediately or you can select it from a list of options. In the Windows Task Manager's Processes tab, you should be able to find "firefox.exe" in the Image Name column. (Left-clicking the Image Name column will sort the names alphabetically, and then you can scroll up or down looking for "f".) Left-click on that "firefox.exe" and then left-click the "End Process" box. A warning box should then pop up, asking if you're really sure you want to terminate the process. Answer Yes. Then wait a few seconds for disk activity to die down. Then re-launch Firefox as you would normally.

  • Bex " the program will now terminate" during the save to favorite

    Hello everybody,
    Ihave a Bw 7.1 system installed with Frontend 720 and bex 700 shared by Citrix.
    I have this error "a critical program error as occurred - the program will now terminate" when I try to save as favorite into my Bw system in BEX .
    The problem doesn't appear when I do this activity by my PC without Citrix.
    Anybody may help me to understand how to solve this issue?
    regards
    Lopresti

    Dear Jelina,
    Have you tried to install the latest frontend patches from Marketplace. If not node, I would suggest you to
    please upgrade to latest,
    Please goto
    -> http://service.sap.com/patches
    -> Browse our Download Catalog
    -> SAP Frontend Components
    -> BI ADDON FOR SAP GUI
    -> BI 7.0 ADDON FOR SAP GUI 7.20
    -> BI 7.0 ADDON FOR SAP GUI 7.20
    -> Win32
    -> Apply the latest.
    For 3.x frontend:
    -> http://service.sap.com/patches
    -> Browse our Download Catalog
    -> SAP Frontend Components
    -> BI ADDON FOR SAP GUI
    -> BW 3.5 ADDON FOR SAP GUI 7.20
    -> BI 3.5 ADDON FOR SAP GUI 7.20
    -> Win32
    -> Apply the latest.

  • Adobe bridge cc is not working on my mac snow leopard version 10.6.8. In other words the program will not open all other programs work fine

    Adobe bridge cc is not working on my mac snow leopard version 10.6.8. In other words the program will not open, but all other programs i have been able to open just fine

    Moving this discussion to the Bridge General Discussion forum.

  • Terminal will not terminate after Yosemite upgrade

    When attempting to close Terminal, or when attempting to logout or shutdown, the Terminal will not terminate, but displays the following dialog: "Do you want to close this window? Closing this window will terminate the running processes: ."  Also, the red "close" icon shows a dot instead of an "x" inside, indicating the running process.  However there is NO running process (that I started) other than the terminal's own Bash shell.
    PS indicates only 3 user terminal processes, each the root Bash process running on the terminal:
    $ ps
      PID TTY           TIME CMD
    2816 ttys000    0:00.02 -bash
    2817 ttys001    0:00.01 -bash
    2818 ttys002    0:00.01 -bash
    ps -ef shows no child processes (other than the ps and grep processes:
    $ ps -ef | grep 2816
      501  2816  2813   0 10:58AM ttys000    0:00.02 -bash
        0  2868  2816   0 11:05AM ttys000    0:00.00 ps -ef
      501  2869  2816   0 11:05AM ttys000    0:00.00 grep 2816
    This behavior occurs no matter if I quit Terminal and restart it or any other combination of options.
    This behavior is new with Yosemite.  Version 10.10 is installed on a late 2009 iMac.
    Thanks

    Check the Ask before closing setting in the Terminal preferences dialog.

  • I have a Mac running OS 10.5.8. I downloaded Firefox 4 and not the program will not open at all. I am also unable to download the previous version that was running fine. I'm using Safari to contact you.

    I have a Mac G5 running OS 10.5.8. I downloaded Firefox 4 and now the program will not open at all. I get an error message that reads --
    "You cannot open the application 'Firefox" because it is not supported on this architecture."
    I am also unable to find a link to download the previous version (3.6) that was running fine. (I'm using Safari to contact you.)

    Same proble here, although the Firefox system requirements says it is OK to have PowerPC G3 G4 or G5 ( I have G5 2GHZ)
    My solution; very simply use timemachine to restore the previous Frefox 3.x
    worked great in 3 mns

  • My firefox installation is complete on my PC with Win XP, the icons are up, but the program will not start... no process or anything in task manager... any idea what is going on?

    bought a second hand laptop running Windows xp. When I go to download firefox, the installation goes seemingly smooth, but the program will not open. There are no firefox processes showing in task manager when I do this. I just downloaded chrome instead, but it sucks and I want firefox but my computer rejects it. This computer runs every other program I use without a hitch
    == This happened ==
    Every time Firefox opened
    == after installation ==
    == User Agent ==
    Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4

    thanks chris for the reply back,i have solved the massive problem i have had with MF 3.6.3 it ws COMODO FREE FIREWALL i had a sneaking suspicion all a long it could have been that but was not sure?,my pc had slowed down since installing comodo i am pretty sure of that,there were lags and pauses ect ect on general usage of the pc even though cpu usage was ok?,so maybe if many pc users that have comodo firewall installed they might like to try a change to another firewall and see if it helps,i went back to OUTPOST FREE FIREWALL which i had for ages without ANY problems whatsoever.
    regards
    john
    mozilla firefox build 3.6.3

  • I have Photoshop Elements 9 on an iMac with OS 10.6.8. I bought a new printer/scanner and the program will not import the new scanner to replace the old one. How do I do this?

    I have Photoshop Elements 9 on an iMac with OS 10.6.8. I bought a new printer/scanner and the program will not import the new scanner to replace the old one. How do I do this?

    Thank you for your suggestions. I downloaded a more recent version of Twain, but this didn't help. I also tried closing and opening Photo Shop and restarting my computer without success. Reinstalling Photo Shop sounds like a very promising solution, but I'm  not sure I will do it. In the meantime I can scan items using a printer program. These scans open in Photo Shop. It is an extra step.

  • My adobe CS2 programs will not open on my macbook pro osx 10.5.8

    Today my adobe cs2 suite programs will not open.  They were working just fine a couple of days ago.  And they have worked fine for years.  I did not update to any new os that would cause them not to work.  I really need to get some image work done soon and this is a real monkey wrench in my plans.  I uninstalled everything and tried to reinstall from the disc and it would not let me do that either.  I tried to download picasa just as a quick alternative to get some images edited tonight and it would not let me open that either, even though it said it was good for 10.5 or above.  So the only thing I can think of is that I downloaded something that changed some settings? 

    Try http://www.lemkesoft.com/ GraphicConverter instead.
    Mackeeper can also be a problem:
    https://discussions.apple.com/docs/DOC-3036

  • HT1918 I have a new visa debit card, I have tryed several times to put in this new information into my IPad. The program keeps telling me. There's a billing problem with a previous purchase. Please update your payment method. The program will not let me u

    I have a new visa debit card, I have tryed several times to put in this new information into my IPad. The program keeps telling me.
    There's a billing problem with a previous purchase. Please update your payment method.
    The program will not let me update, what am I doing wrong. rose165

    I would love to have a phone number to call someone with apple on this issue.

  • I updated Pages two months ago, yet my gmail program will NOT send out a pages document and a pages file I saved to desktop will NOT open and a box pops up telling me it won't open document without the Pages upgrade WHICH I HAVE ALREADY DONE...PLEASE HELP

    I updated Pages two months ago to the latest version.  BUT, my MAIL program will not allow me to send documents I attach that are genereated witht eh update Pages.  And, when I save a doc to desktop generated in Pages, it will not opena, a box pops up and tells me the it wil not open until I have upgraded to the new PAges, WHICH I HAVE ALREADY DONE!!!  What is UP with this, can anyone please help me?  Would GREATLY appreciate it.
    SA

    Pages 5 is in a new format that is not compatible with GMail, Google, Amazon, DropBox and other 3rd party servers.
    Peter

  • Programs will not open from Dock

    I have updated my Macbook Pro with Yosemite which has led to - a lot. Programs will not open from Dock, they are just revealed in Finder. Scrolling with mousebuttons in a browser will zoom instead of scroll, the courser will not change after changing tool in Indesign. Just to mention a few problems i have discovered so far. I think I was an idiot to uppgrade to Yosemite. PLEASE HELP!

    Open Disk Utility and Repair Permissions, then quit DU and Restart the MBP.  If that does not clear the issues, restart again holding the Command and R keys, and from Utilities on the menu bar select Install Mac OS X.  That will reinstall Yosemite but leave your content and settings intact.  See if that repairs whatever is broken.

  • TS2972 First night I was able to watch 2 TV shows (45 min each) with no problems, but thereafter programs will not stream without constant pause to buffer. Weather conditions are ideal and my internet comes from crappy hugesnet, but worked fine the first

    First night I was able to watch 2 TV shows (45 min each) with no problems, but thereafter programs will not stream without constant pause to buffer. Weather conditions are ideal and my internet comes from crappy hugesnet, but worked fine the first night.

    The speed may have been ok at that time and is too inconsistent/too slow overall. interference may have proven to be more of an issue since as well. If using public DNS that will provide Intermittant results
    I'm sure using a hotspot would be fine but it depends on your viewing habits. An HD movie is around 4-5GB. It would also be subject to speed. requirements so best to test to see how it compares.
    You would have to check with your Carrier if hotspot it's enabled then just to into your settings and toggle it ON

  • Pages is not responding, the icon comes up but the program will not open????

    Pages is not responding, the icon comes up but the program will not open????

    You have to give us some more information or do a search in the forum for answers on the same matter.

  • I Just bought iMovie for yosmite and the program will not open.. I will like a fix or a refund..

    I Just bought iMovie for yosmite and the program will not open.. I will like a fix or a refund.. i am getting tired of these problems...

    Welcome to the world of downloaded software. There are no refunds.
    Back in the good old days when software was purchased on disk one could sell it (legally).
    Please describe your problem.  Give us some details to go from.   Are you using iMovie 06, or something newer?

Maybe you are looking for

  • Devolução de Transferência SD/MM com NF

    Prezados bom dia, Tenho o processo de transferência SD/MM (Mov 861/861) e agora me foi solicitado a criação do processo de devolução de transferência onde, segundo o fiscal, não podemos fazer simplesmente um outro PC UB para devolver a mercadoria. Pe

  • Can you copy Subtitle Streams from one project to another?

    I inserted subtitles onto a track and would like to use the same subtitles on a new track; can I copy them and paste them into the new project? How can I do this? Many thanks!

  • How do I create another library in itunes?

    In itunes, it tells me to hold down the shift key while opening itunes and that will prompt me to create a new library but that does not work.

  • How do I get rid of blurred text happens all the time now in Firefox web browser?

    Even when I was registering for this forum the text was blurred and multicolored sometimes. Its very annoying and hard to see. This is all the time with Firexfox. Chrome and IE I have no such issues. Also when I was taking an assessment test for a jo

  • Calling remote procedure through database link

    Hi, I have a procedure in a package with a type I delcared as follows: Database1 : create or replace package p1 is TYPE dependents_rec IS RECORD ( name VARCHAR2 (80), dob date); TYPE dependents IS TABLE OF dependents_rec INDEX BY BINARY_INTEGER; proc