Repost as question for points: What did I do wrong? (Try and Catch program)

This has to be a try and catch program.
This is the given output sample:
OUTPUT SAMPLE #2 for input.txt: 12345 222256 -3 123 -56784 555557 6345678 x x x 81234 121212 x x 123434 x x 1009098 2099
Please input the name of the file to be opened: input.txt
For number 12345 the sum of digits is: 15
For number 222256 the sum of digits is: 19
Found an integer (-3), but it is negative. Will ignore!
For number 123 the sum of digits is: 6
Found an integer (-56784), but it is negative. Will ignore!
For number 555557 the sum of digits is: 32
For number 6345678 the sum of digits is: 39
For number 81234 the sum of digits is: 18
For number 121212 the sum of digits is: 9
For number 123434 the sum of digits is: 17
For number 1009098 the sum of digits is: 27
For number 2099 the sum of digits is: 20
Here is what I have so far.
import java.util.Scanner;
  import java.io.*;// FileNotFoundException
public class Assignment3b {
  public static void main (String[]args){
    Boolean fileOpened = true; 
    String fileName;
    int n,mod=0,sum=0,t=0;
    Scanner inputFile = new Scanner(System.in);
    System.out.print("Please input the name of the file to be opened: ");
    fileName = inputFile.nextLine();
    System.out.println();
    try {
            inputFile = new Scanner(new File(fileName));
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        if (fileOpened) {
          while (inputFile.hasNext()){
            if (inputFile.hasNextInt()){
              n = inputFile.nextInt();
              t=n;
              while(n>0){
                mod = n % 10;
                sum = mod + sum;
                n = n/10;
              System.out.println ("For number " + t + " the sum of digits is : " + sum);
              mod = 0;
              sum = 0;
              while (n<0) {
                System.out.println ("Found an integer (" + t + "), but it negative. Will ignore!");
                inputFile.next();
                n = inputFile.nextInt();
            else {
              inputFile.next();
}Everything seems to work fine until, it is time to deal with negative numbers. How can I fix this. Please put your reply in layman's terms to the best of your ability.
Thanks and God Bless.

// COSC 236                                Assignment # 3
// YOUR NAME: Anson Castelino
// DUE-DATE:
// PROGRAM-NAME: Assignment # 3 Prt2
//import packages
  import java.util.Scanner;
  import java.io.*;// FileNotFoundException
public class Assignment3b {
  public static void main (String[]args){
    Boolean fileOpened = true; 
    String fileName;
    int n,mod=0,sum=0,t=0;
    Scanner inputFile = new Scanner(System.in);
    System.out.print("Please input the name of the file to be opened: ");
    fileName = inputFile.nextLine();
    System.out.println();
    try {
            inputFile = new Scanner(new File(fileName));
        catch (FileNotFoundException e) {
            System.out.println("--- File Not Found! ---");
            fileOpened = false;
        if (fileOpened) {
          while (inputFile.hasNext()){
            if (inputFile.hasNextInt()){
              n = inputFile.nextInt();
              t=n;
              while(n>0){
                mod = n % 10;
                sum = mod + sum;
                n = n/10;
              System.out.println ("For number " + t + " the sum of digits is : " + sum);
              mod = 0;
              sum = 0;
              if (n<0) {
                System.out.println ("Found an integer (" + t + "), but it is negative. Will ignore!");
                inputFile.next();
              inputFile.hasNext();
            else {
              inputFile.next();
}Updated code.
current output is as follows:
Please input the name of the file to be opened: [DrJava Input Box]
For number 12345 the sum of digits is : 15
For number 222256 the sum of digits is : 19
For number -3 the sum of digits is : 0 <-------- this part is not suppose to be here.
Found an integer (-3), but it is negative. Will ignore!
For number -56784 the sum of digits is : 0 <-------- this part is not suppose to be here.
Found an integer (-56784), but it is negative. Will ignore!
For number 6345678 the sum of digits is : 39
For number 81234 the sum of digits is : 18
For number 121212 the sum of digits is : 9
For number 123434 the sum of digits is : 17
For number 1009098 the sum of digits is : 27
For number 2099 the sum of digits is : 20
>

Similar Messages

  • I seem to not enter the correct answers to my security questions for itunes to buy an in-app purchase and also cannot answer the questions exactly like i answered them when creating the account for my ipod, how do i find out what answers i put

    I seem to not enter the correct answers to my security questions for itunes to buy an in-app purchase and also cannot answer the questions exactly like i answered them when creating the account for my ipod, how do i find out what answers i put for my ipod touch and itunes?

    Try these previous discusssions:
    recover answers to security questions: Apple Support Communities
    how do i change apple ID security...: Apple Support Communities

  • I just updated my iPad to OS5 and all of my apps are gone. What did I do wrong and how can I get them back? Several were paid for. Thanks

    I just updated my iPad to OS5 and all of my apps are gone. What did I do wrong and how can I get them back? Several were paid for. Thanks

    If you have failed to make sure that any apps purchased on the iphone were transferred to your computer before updating, then you will have to redownload.
    Open itunes store, click Purchased, under Quick Links.

  • I have a question for apple I bought a 15$ iTunes card and got to movie rentals it's been 3 days and the movie bearlly downloaded onced it finished it restarted it self I want my money back....what do I do

    I have a question for apple I bought a 15$ iTunes card and got to movie rentals it's been 3 days and the movie bearlly downloaded onced it finished it restarted it self I want my money back....what do I do

    You will have to contact Apple/iTunes support, we are just other users like you, not Apple employees.
    http://www.apple.com/support/itunes/contact/
    You can also Report a Problem with the rental in iTunes on your computer.
    http://appletoolbox.com/2012/03/how-to-report-a-problem-for-an-iphoneipadipod-to uch-app/

  • I was setting up my IPod Nano 7 for the first time and I can't play the songs I bought. What did I do wrong?

    I was setting up my IPod Nano7 for the first time and purchased 3 songs.  When I went to play it on my IPod the screen said "No Music".  What did I do wrong?

    We are going through same thing and looks like alot of other people also. Seems to me Apple would have invalid email instead of us loosing the gift card all together. Very irratating. Good Luck.

  • What did i do wrong

    I inserted a new method into the code, and it seems to work alright, but it doesn't solve the problem.
    import java.util.*;
    public class Summer
       public static void main (String[] args)
         Scanner in = new Scanner(System.in);
         int first = 0;
         int last = 0;
         int total = 0;
         int i = 0;
         System.out.println("Hello. I will calculate the sum");
         System.out.println("of consecutive integers.");
         System.out.println("Please enter the starting number:");
         first = in.nextInt();
         System.out.println("Please enter the ending number:");
         last = in.nextInt();
         while (last < first)
           System.out.println(last + " is smaller than " + first);
           System.out.println("The ending number must be bigger than the first");
           System.out.println("Enter the starting number again");
           first = in.nextInt();
           System.out.println("Enter the ending number again");
           last = in.nextInt();
           System.out.println("The sum of the numbers are " + total);
           total = sum(last, first);
                 for (i = first; i <= last; i++)
             total = total + i;     
                  public static int sum(int num1, int num2)
                       int result;
                       result = num1 + num2;
                       return result;
    }what did i do wrong?

    I'm going to try to list the things you could fix here to make this better code. It might seem like a lot and I'm not trying to be mean or rude, I'm just trying to be helpful.
    First this part of your code:
    System.out.println("Hello. I will calculate the sum");
         System.out.println("of consecutive integers.");
         System.out.println("Please enter the starting number:");
         first = in.nextInt();
         System.out.println("Please enter the ending number:");
         last = in.nextInt();
         while (last < first)
           System.out.println(last + " is smaller than " + first);
           System.out.println("The ending number must be bigger than the first");
           System.out.println("Enter the starting number again");
           first = in.nextInt();
           System.out.println("Enter the ending number again");
           last = in.nextInt();
           System.out.println("The sum of the numbers are " + total);
           total = sum(last, first);
         }This code is repetitive and can be shortened greatly. Notice that the result you are looking for is that the number "last" entered is greater than first. So why not begin the loop right away like this to reduce your code by almost half?:
    // bring this outside of the loop so that it only shows once
    System.out.println("Hello. I will calculate the sum");
    System.out.println("of consecutive integers.");
    // last and first are originally set equal to 0 so this loop will begin right away
    while (last <= first) {    
         System.out.println("Please enter the starting number:");
         first = in.nextInt();
         System.out.println("Please enter the ending number:");
         last = in.nextInt();
        // add an if statement to print the please re-enter message
       if (last <= first) {
           System.out.println(last + " not larger than " + first);
           System.out.println("The ending number must be bigger than the first");
    }Second,
    The total part should not be in the loop. Notice how in your original code, the total was inside the loop so even if incorrect numbers were entered, the total would be displayed. The user would then be asked to enter new numbers and the total would be displayed again. I am assuming that the wanted behavior is to only display the total when correct numbers are entered. So we need to take the total out of the loop.
    Third,
    in your orignal code:
    System.out.println("The sum of the numbers are " + total);
           total = sum(last, first);Here you are printing the value total before the total is calculated. That means that the value shown in the print will be incorrect. You must calculate the value of total before printing it.
    I think this will get to the point where the code is almost what you are looking for.
    Right now, your sum method simply adds the two numbers together, which could be done with a simple + sign, rather than writing a new method.
    The for loop which I can see in your code looks like it will perform the action you are looking for.
    What you need to do is move this for loop to the line just above the line where you are printing the total.
    This means that the for loop will calculate the total, and then print it. If you print the total before calculating it you won't see the right value.
    I hope this was clear and that it helped,
    let me know if you have more questions and I will try to be more clear.

  • I updated my iPhone today over wifi.  It downloaded 6.1.3 completely and started then installed it.  After the install all it does is show the connect to iTunes screen.  What did I do wrong and now do I have to completely restore the phone?

    I updated my iPhone today over wifi.  It downloaded 6.1.3 completely and started then installed it.  After the install all it does is show the connect to iTunes screen.  What did I do wrong and now do I have to completely restore the phone?

    Next question.... I did an iCloud save point earlier today so in theory everything should have been saved and the restore won't be a complete loss right?  Please tell me my pics aren't gone.....
    Thanks for the help.

  • When user clicks on "Like Button," the counter increases but nothing shows up showing the user recommends my site to their friends. What did I do wrong?

    When user clicks on "Like Button," the counter increases but nothing shows up showing the user recommends my site to their friends. What did I do wrong?
    I used the iframe code from Facebook's "Like Button" site; and inserted the code in the html widget popup box, then positioned it where I wanted it on my page and published. It looks fine (though I had to add "http" before my url to get it to show up).
    So, when a user clicks on button, a pop-up opens asking for Facebook password. When I (the user) enter a password, nothing happens after that. I thought the idea was that a user would be able to show their friends that they like my website. After I entered my password in pop-up after clicking on "Like" I went to my facebook page (a company page) to see if it showed that I (the user that clicked on "Like" on iweb) recommended the website. But nothing showed up. I thought maybe it was because Facebook associated my password as the admin for the Facebook page so didn't count it. But a friend tried it and same thing happened. I went back and on one page I put in another facebook code for a combo Like/Send button. It shows up but acted the same as the regular Like button.
    Questions:
    1. Is this the way the Like Button is suppose to work? Only benefit of Like button being that it just counts the clicks on the Like button and does NOT let users share their recommendation with their friends?
    2. If it's suppose to let users share their "Likes" with their friends, what did I do wrong? There were three types of code but in reading discussions, they all say to use iframe. (I used the first choice which I think was html for Javascript SDK and put that in my HTML Snippit box and the Like/Share button showed up on my iweb page next to the facebook icon and the words "likes this" but when I click it, I don't see instructions that it's sending my recommendation to my friends.)
    I must have done something wrong, but can't figure out what. Does anyone know? If the only benefit of the Like Button is the counter, it doesn't seem worthwhile.
    Thanks to anyone who can figure this out!  My website is couponsforfun.com

    You want something like this?
    http://home.wyodor.net/demoos/facebook/
    The send button sends the link to their friends in the address field with a message.
    They recieve a message in the inbox.
    There's no post on a page.
    If they want that, then they should share the link themselves.
    Perhaps it's best to study what facebook has to offer and how it works instead of guessing what it is supposed to do and be disappointed.

  • I had microsoft exchange added and when I synced I lost all of my prior contacts. Also, thenames all turned to numbers.  Example when you get a text from a contact, their name appeared.  Now just a phone number.  What did I do wrong and can I get it back?

    Since adding microsoft exchange I sunced my phone and lost all of my old contact, notes. etc.  Also, when I do get a text message it appears as a number instead of a name.  What did I do wrong and can I get my old info restored.  When I tried restoring it only gave me the same thing.

    That number is for an apple server in the UK that is used for iMessage activation.  A hidden SMS is snet to that number when you turn iMessage on and is used to verify your phone number.  I suggest you turn iMessage off.  In settings/phone turn on dial assist.  Check with your carrier to see if you can send an international SMS as you end that possibility to activate iMessage.  Rest your phone (Hold down the Sleep/Wake button and the home button together until the apple logo appears (ignore the ON/OFF slider) then let both buttons go and wait for device to restart (no data will be lost).) then turn iMessage back on.

  • Music not recognized from old PC to new, what did i do wrong.

    So i just got a new PC.  I saved my entire Itunes file on an external hardrive.  The music all transfers to the new PC and i loaded it into the newest Itunes.  I authorized the new computer through Itunes and got all artwork.  Now i cannot play songs or transfer music to my i-pod.  I had to rboot the Ipod. so now i have an empty Ipod and a bunch of Music I cannot play.  I've connested my Iphone and it seems to recognize it, but I'm afraid to connest it again until i trust the itunes to work.  When I try to play a song it say cannot locate the original/
    What did i do wrong?  What can I do?  I still have the old tower available to retreive Itunes
    Thanks for any advice
    MJ

    The index page copied from the template is now reading the css.  I did nothing other than shut down DW and open it again.  Maybe it just takes a while for the process to complete.  Am now creating more pages that are also not reading css.  Will do the same and see if it all connects.

  • My husband and I did the most recent update. Now when we send messages to each other we also receive a duplicate of the message to ourself, what did we do wrong?

    My husband and I did the most recent update. Now when we send messages to each other we also receive a duplicate of the message to ourself, what did we do wrong?

    Check to see if you are both using the same Apple ID for iMessage.  If you are, one of you should go to Settings>Messages>Send & Receive, tap the ID, sign out, then sign back in with a different ID.  (You can continue to share the same ID for other services such as iTunes.)

  • EMac Freezes while running Diskwarrior!  What Did I Do Wrong?

    I just purchased Diskwarrior upon the suggestion of several people here, and decided to try it out. I booted up from the DiskWarrior CD, and followed instructions. It said HD was ready to rebuild and I clicked on that. It went for awhile and then just froze. I had to turn the power off to get out of the program and back to my my startup disk.
    What did I do wrong? Is there more to installing it than just booting up from the CD? I need some great advice! Thanks.

    Janice,
    You're certain DW really froze? It takes typically about 45 minutes to process a half-full 40 GB HD on my 700 MHz eMac, and at some parts of the run it does appear as if the progress bar isn't moving, but it does come back to update the screen eventually.
    The only times I can recall reports of Disk Warrior failing all ended up being traced to hardware failure of one kind or another (bad RAM in particular). What version of Disk Warrios do you have? The version number will be printed on the DW CD. Since your profile shows OS X 10.3.9, through, any DW recently purchased from Alsoft should work with your Mac. Have you checked the disc for smudges or scratches?
    Dig out your Apple Hardware Test (AHT) disc and see if your Mac will boot from that and if so what it says about the optical drive. You may need to run a CD lens cleaner through the drive one or two passes. Also have AHT check the RAM; you can also use Memtest.
    The other thing that comes to mind is to try DW with all peripherals other than keyboard and mouse disconnected.

  • All my Photos disappeared after I saved a photo from an email from my wife. I am running Mountain lion on Mac book pro 2012, help. What did I do wrong?

    All my Photos disappeared after I saved a photo to Iphoto from an email from my wife. I am running Mountain lion on Mac book pro 2012, help. What did I do wrong?

    Apply the two fixes below in order as needed:
    Fix #1
    Launch iPhoto with the Command+Option keys held down and rebuild the library.
    Since only one option can be run at a time start with Option #3, followed by #4 and then #1 as needed.
    Fix #2
    Using iPhoto Library Manager  to Rebuild Your iPhoto Library
    1 - download iPhoto Library Manager and launch.
    2 - click on the Add Library button, navigate to your Home/Pictures folder and select your iPhoto Library folder.
    3 - Now that the library is listed in the left hand pane of iPLM, click on your library and go to the File ➙ Rebuild Library menu option.
    4 - In the next  window name the new library and select the location you want it to be placed.
    5 - Click on the Create button.
    Note: This creates a new library based on the LIbraryData.xml file in the library and will recover Events, Albums, keywords, titles and comments.  However, books, calendars, cards and slideshows will be lost. The original library will be left untouched for further attempts at fixing the problem or in case the rebuilt library is not satisfactory.
    OT

  • Video too bright! What did I do wrong?

    The following was shot using a Canon GL2 inside a theater. The stage lights reflected so much the colors and details became washed out. I can't even fix it in Final Cut Pro. What did I do wrong? The camera was set on "Easy Recording" so I know white balance was automatically set.
    Here are some shots
    http://www.youtube.com/watch?v=f7buysQTMPg
    Each shot is followed by an attempt to correct the image. As you can see, I wasn't successful.

    Sorry, I'm a complete beginner to this line of work
    It's a good thing you didn't decide to be a doctor or mechanic or ...
    You should probably try to work for a local production company before trying to tackle any jobs by yourself. Especially if people are depending on you to deliver an acceptable product. That will give you the opportunity to learn how to shoot properly and learn the ins and outs of a video camera.
    As Alchroma said, you white balance manually BEFORE the performance. During the performance you manually control the focus and iris (and panning and zooming).
    Spotlight mode isn't infallible. In fact, it may not be able to handle stage lighting very well at all. Learn how to properly operate the camera you've chosen before committing to doing any work of this nature for pay.
    -DH

  • Nesting: What did I do wrong?

    I just put together 4 shows that were all using the same credits. i created the credits in a new timeline, dragged that sequence to the viewer and then overwrote it into the end of the other 4 sequences.
    I had to make a change to the credits, opened the master credit sequence updated and re-rendered. The updated version did not pass down to the other sequences. I had to go into each sequence, double-click on the credits in the sequence and update each one individually. In the end I had 5 credits sequences open (the original + 4), yet there's only 1 credits sequence in the bins.
    What did I do wrong, shouldn't the 4 shows update automatically when I change the master credit sequence?
    Thanks.

    I had a nesting nightmare in my project. There were nested sequences inside of other nested sequences to keep things organized. What I ended up dong was creating an entirely new final sequence. Then after all the changes were made in all the nests, I opened each nest one at a time, copied all the clips in it, pasted it into the new sequence, made a fresh nest of the clips, then did the same for the next sequence. This way nothing was more than one nest deep in the timeline, and everything was fresh. I made some changes after that and didn't have any issues.
    It worked as a fix but I will be interested in watching the thread to see if someone has the solution to this issue.

Maybe you are looking for

  • Videochat not possible this computer does not support video chats

    Hi there, since yesterday its not possible to to start an video chat. It's grey. In the preference of "mesage" under the tap "video" shows the message "this computer does not support video chats. There is no problem with the camera, i can use facetim

  • 2nd user can't access internet

    I set up a 2nd user account on my Mac and I can't access the internet from it.  I've checked my Network settings and it says everything is working normal.

  • Any Suggestions for this Table??

    Iam facing problem while creating a report. I have to generate a report which is having dynamic columns and rows For Eg. In this report I have total 365 columns (M1 to M365)depends up on the user he can generate the report for 2 or 3 or may be 365 co

  • Accessing Business Graphics using the WebDynpro API

    I would like to access Business Graphics created with IGS using the WebDynpro Business Graphics API. I have no problem displaying the graphic in WebDynpro UI, but i have no idea how to access the binary data of the graphic to work with it outside of

  • Deleting a transported query in QA system

    hi all, i am trying to delete a query in a QA system. the report needs to be deleted due to the errors in naming convention. so my question is: 1) is there a standard way to delete query (bw odjects) that has been transported in QA system? the report