Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: reading a stream of numbers from standard input

  1. #1
    Member
    Join Date
    Mar 2009
    Posts
    91
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default reading a stream of numbers from standard input

    guys, I'm trying to read a stream of numbers from standard input like: 2 3 -3 10 44 9 -1. The line ends once it read -1, but for some reason I have an endless loop... how could I read this stream of numbers one number at a time?

    int num[] = new int[5];
            char ch;
     
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("enter series of number: ");         
            int i = 0;
             do{ 
                 num[i] = bf.read();
                 i++;                     
            }while(num[i] != -1);
     
             int j = 0;
             while(j < num.length) {
                 System.out.println(num[j]);
                 j++;
             }


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: reading a stream of numbers from standard input

    you could println your variables each step of the way, and see what is going on...

  3. #3
    Member
    Join Date
    Mar 2009
    Posts
    91
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: reading a stream of numbers from standard input

    Quote Originally Posted by jps View Post
    you could println your variables each step of the way, and see what is going on...
    I'm getting a bunch of strange numbers... I don't think I'm reading the correct input. At the same time I'm getting an outofboud exception. like I'm going beyond the 5 elements of the array

    enter series of number: 
    10 3 4 99 -1
    49
    48
    32
    51
    32
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    	at wordset.Stack.main(Stack.java:67)
    Java Result: 1

  4. #4
    Junior Member
    Join Date
    Jul 2012
    Posts
    17
    Thanks
    1
    Thanked 3 Times in 3 Posts

    Default Re: reading a stream of numbers from standard input

    read() returns a character, not a parsed integer... read() will return, in order: '1' (49), '0' (48), ' ' (32), '3' (51), ' ' (32), '4' (52), ' ' (32), '9' (57), '9' (57), ' ' (32), '-' (45), '1' (49) i.e. each character is read as it's encoded form according to ASCII, as seen below.

    One solution is to use a Scanner, particularly with nextInt():
      /* why hardcode the length? */
      final int[] num = new int[5];
      final Scanner scanner = new Scanner(System.in);
      System.out.println("enter series of number: ");         
      int ch;
      int i = 0;
      while (scanner.hasNextInt() && (ch = scanner.nextInt()) != -1) {
        num[i++] = ch;
      }
      int j = 0;
      while (j < 5) {
        System.out.println(num[j]);
      }
    Last edited by veeer; July 30th, 2012 at 08:06 AM.

  5. The Following User Says Thank You to veeer For This Useful Post:

    Badger191 (July 24th, 2012)

  6. #5
    Junior Member hackthisred's Avatar
    Join Date
    Apr 2012
    Posts
    18
    Thanks
    1
    Thanked 1 Time in 1 Post

    Lightbulb Re: reading a stream of numbers from standard input

    Quote Originally Posted by mia_tech View Post
    guys, I'm trying to read a stream of numbers from standard input like: 2 3 -3 10 44 9 -1. The line ends once it read -1, but for some reason I have an endless loop... how could I read this stream of numbers one number at a time?

    int num[] = new int[5];
            char ch;
     
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("enter series of number: ");         
            int i = 0;
             do{ 
                 num[i] = bf.read();
                 i++;                     
            }while(num[i] != -1);
     
             int j = 0;
             while(j < num.length) {
                 System.out.println(num[j]);
                 j++;
             }
    I'd recommend the following approach...
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
     
    public class InputStuff {
     
    	private List<Integer> getUserInput()
    	{
    		List<Integer> list = new ArrayList<Integer>();
    		Scanner keyboard = new Scanner(System.in);
    		while(keyboard.hasNext())
    		{
    			String input = keyboard.next();
    			if(!input.equals("-1"))
    				list.add(Integer.parseInt(input));
    			else
    				return list;
    		}
    		return list;
    	}
     
    	public static void main(String[] args)
    	{
    		for (Integer number  : new InputStuff().getUserInput()) 
    		{
    			System.out.print(number + " ");
    		}
    	}
    }
    f34r th3 kut3 1z

  7. #6
    Junior Member
    Join Date
    Jul 2012
    Posts
    17
    Thanks
    1
    Thanked 3 Times in 3 Posts

    Default Re: reading a stream of numbers from standard input

    Quote Originally Posted by hackthisred View Post
    I'd recommend the following approach...
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
     
    public class InputStuff {
     
    	private List<Integer> getUserInput()
    	{
    		List<Integer> list = new ArrayList<Integer>();
    		Scanner keyboard = new Scanner(System.in);
    		while(keyboard.hasNext())
    		{
    			String input = keyboard.next();
    			if(!input.equals("-1"))
    				list.add(Integer.parseInt(input));
    			else
    				return list;
    		}
    		return list;
    	}
     
    	public static void main(String[] args)
    	{
    		for (Integer number  : new InputStuff().getUserInput()) 
    		{
    			System.out.print(number + " ");
    		}
    	}
    }
    Really? Your approach would be to make a dedicated instance method to invoke on an object that has no real purpose? You'd manually read a token using scanner.next() and *then* parse it as an integer? You'd compare the input to -1 via string equality rather than just comparing integers? You have two identical return statements when one could just be replaced by a break?

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Scanner;
     
    public final class EchoSeries {
     
      private EchoSeries() { }
     
      static List<Integer> readSeries() {
        final Scanner scanner = new Scanner(System.in);
        final List<Integer> list = new ArrayList<Integer>();
        int n;
        while (scanner.hasNextInt() && (n = scanner.nextInt()) != -1) {
          list.add(n);
        }
        return list;
      }
     
      public static void main(String[] argv) {
        final List<Integer> series = readSeries();
        for (final int n : series) {
          System.out.println(n);
        }
      }
    }

  8. The Following User Says Thank You to veeer For This Useful Post:

    Badger191 (July 24th, 2012)

  9. #7
    Junior Member hackthisred's Avatar
    Join Date
    Apr 2012
    Posts
    18
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: reading a stream of numbers from standard input

    Because in larger codes static methods are bad, when trying to trouble shoot code on an enterprise level. Besides I'd assume this method would be used inside a class without a main() lol.

    So what's the big deal, reading in a string from the user and parsing it to an Integer... I didn't break any coding rules, one can use either or... and who cares that I used a 'return' instead of a break they can be used interchangeably in this instance.
    f34r th3 kut3 1z

  10. #8
    Junior Member
    Join Date
    Jul 2012
    Posts
    17
    Thanks
    1
    Thanked 3 Times in 3 Posts

    Default Re: reading a stream of numbers from standard input

    Static methods are bad? So Math.sin is bad, eh? I understand what you're trying to say, but this is clearly not enterprise scale... you appear to have to some degree a naive understanding of unit testing via mocking. Not trying to start a fight, just pointing out flaws in your code. You can choose to acknowledge them.

Similar Threads

  1. I/O stream for reading and editing a file full of numbers
    By Harry Blargle in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: October 5th, 2011, 09:00 AM
  2. could not create audio stream from input stream
    By chronoz13 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: June 2nd, 2011, 02:08 AM
  3. reading stream of bytes from serial port
    By KrisTheSavage in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: January 3rd, 2011, 11:02 AM
  4. url input stream returning blank
    By yo99 in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: June 2nd, 2010, 08:14 PM
  5. Client input Stream
    By gisler in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: December 19th, 2009, 09:30 PM