Results 1 to 2 of 2
  1. #1
    DanPe is offline Member
    Join Date
    May 2012
    Posts
    4
    Rep Power
    0

    Default Question: Loops, Positive ints etc...

    Hi again my friends,
    I encountered the following question:
    "Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, each followed by a space, and that terminates when it reads an integer that is not positive. Declare any variables that are needed."

    In order to solve the exercise I wrote the following code which seems to work. However, I was wondering if this really is the correct way to solve the question. If it's not, do you think it's an acceptable solution or would I get some points detracted for this code.
    Would love to hear your opinion. Thanks :)

    Java Code:
    import java.util.Scanner;
     
    public class copy {
        public static void main(String[] args)
        {
            Scanner input = new Scanner(System.in);
           
     
            while (true)
            {
                int num = input.nextInt();
                if (num >= 100)
                {
                    System.out.print(num + " ");
                }
                else if (num >= 0 && num < 100)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
            System.out.println("Program terminated");
            System.exit(0);
        }   
    }

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,778
    Blog Entries
    7
    Rep Power
    21

    Default Re: Question: Loops, Positive ints etc...

    I would do it like this:

    Java Code:
    while ((num= input.nextInt()) >= 0) 
       if (num >= 100)
          System.out.print(num+" ");
    (I left out the declaration part and the code doesn't anticipate for incorrect input).

    kind regarrds,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Question concerning loops
    By jim01 in forum New To Java
    Replies: 8
    Last Post: 04-13-2011, 04:17 PM
  2. Question about sentinal loops with strings
    By dienesh77 in forum New To Java
    Replies: 3
    Last Post: 04-06-2011, 02:57 AM
  3. Noob question about using ints in booleans
    By elfdreaming in forum New To Java
    Replies: 6
    Last Post: 03-14-2011, 12:07 PM
  4. Question about loops
    By SwEeTAcTioN in forum New To Java
    Replies: 1
    Last Post: 10-23-2009, 08:15 AM
  5. Question about loops
    By BHCluster in forum New To Java
    Replies: 4
    Last Post: 04-16-2008, 06:40 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •