Results 1 to 2 of 2
- 05-16-2012, 08:51 PM #1
Member
- Join Date
- May 2012
- Posts
- 4
- Rep Power
- 0
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); } }
- 05-16-2012, 09:03 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,606
- Blog Entries
- 7
- Rep Power
- 17
Re: Question: Loops, Positive ints etc...
I would do it like this:
(I left out the declaration part and the code doesn't anticipate for incorrect input).Java Code:while ((num= input.nextInt()) >= 0) if (num >= 100) System.out.print(num+" ");
kind regarrds,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
Question concerning loops
By jim01 in forum New To JavaReplies: 8Last Post: 04-13-2011, 03:17 PM -
Question about sentinal loops with strings
By dienesh77 in forum New To JavaReplies: 3Last Post: 04-06-2011, 01:57 AM -
Noob question about using ints in booleans
By elfdreaming in forum New To JavaReplies: 6Last Post: 03-14-2011, 11:07 AM -
Question about loops
By SwEeTAcTioN in forum New To JavaReplies: 1Last Post: 10-23-2009, 07:15 AM -
Question about loops
By BHCluster in forum New To JavaReplies: 4Last Post: 04-16-2008, 05:40 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks