Results 1 to 13 of 13
  1. #1
    varunb is offline Member
    Join Date
    Jul 2007
    Posts
    3
    Rep Power
    0

    Default Read user input into integer array

    I am trying to get make a java program which takes integers from user & then store into an integer array of length "size". The only problem is that I am getting exceptions when I am about to enter numbers from console. I am using Eclipse IDE & below is my code:


    import java.io.*;
    import java.util.Scanner;
    import java.util.*;

    public class BetterProgrammerTask {

    public static void main(String[] args) throws IOException {
    int size = 0;
    System.out.println("Enter the size of the array: ");
    Scanner in = new Scanner(System.in);
    size = in.nextInt();
    in.close();
    System.out.println("The size you enetered is " + size);
    int[] a = new int[size];

    Scanner in1 = new Scanner(System.in);
    System.out.println("Enter the array: ");

    int j=0;

    while(j<size)
    {
    a[j]=in1.nextInt();
    ++j;
    }
    in1.close();

    Arrays.sort(a);
    System.out.println("The sorted array is ");
    for (int i=0; i<size; i++)
    {
    System.out.println(a[i]);
    }

    }

    }


    Below is the exception message:

    Enter the size of the array:
    11
    The size you enetered is 11
    Enter the array:
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at BetterProgrammerTask.main(BetterProgrammerTask.jav a:33)
    Last edited by varunb; 07-08-2010 at 06:51 PM.

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Get rid of the second Scanner object.
    Java Code:
    Scanner in = new Scanner(System.in);
    size = in.nextInt();
    System.out.println("The size you enetered is " + size);
    int[] a = new int[size];
    System.out.println("Enter the array: ");
    
    int j = 0;
    while (j < size) {
    	System.out.print("Enter "+ (j+1) + ": ");
    	a[j] = in.nextInt();
    	++j;
    }
    in.close();
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    can you explain to the OP what happened and why he got the exception?

  4. #4
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    I can only guess, as I'm not familiar with Scanner, but I reckon it boils down to the inputStream still holding the '\n' from the first nextInt() call, but please correct me if I'm wrong.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    java.util.NoSuchElementException
    If the OP would read the API doc for the Scanner nextInt() method it is explained there.
    After he understands why he gets the error then he needs to look at other Scanner methods to see how he can avoid this error.

  6. #6
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Ok, I've read it and I don't get it. Might be a language thing, but why is the input exhausted?
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    I think exhausted here means that there is nothing more there.

    He needs to test if anything is there by using a hasNext method.
    The problem with that is that it will block waiting for something. A bit confusing to me.
    hasNext() shouldn't block. If there isn't anything return false. I guess it wants to see what the next thing is and test it to be an int (or whatever).
    There might be a method to call to test if the input stream is empty.

  8. #8
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Quote Originally Posted by Norm View Post
    I think exhausted here means that there is nothing more there.
    That's what bugs me, if there is nothing more, it should wait for an input, no?
    Scanner1 has read an input and is closed, fine. Scanner2 should start from scratch, but it doesn't.

    The intro chapter in the API doesn't help much either leave aloe the Scanning tutorial in I/O.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    I can't figure out how you can use Scanner. There appears no way to call a hasNext method without it possibly blocking.
    I can understand the a call to a next method could fail if there isn't anything in the input.

    Here's an attempt not to block on Scanner having nothing to read.The main code is from another forum thread also having Scanner problems.
    Java Code:
    import java.util.ArrayList;
    
    import java.util.Scanner;
    
    // Check if the scanner has any input available
    // Problem because Scanner.hasNext() will block!!
    class CheckScanner {
    
      static boolean hasNext(final Scanner sc) {
        Thread t = new Thread(new Runnable() {
          public void run() {
            sc.hasNext();  // this could block
            System.out.println("hasNext returned");
          }
        });
        t.start();
        try{Thread.sleep(10);}catch(Exception x){};   // is this long enough?
        //If thread still alive, then it must be blocked
        if(t.isAlive()) {
          t.interrupt(); // What does this do for thread blocked on I/O
          System.out.println("interrupt called");
          return false;
        }else{
          return true;  // If thread has  exited, then hasNext() returned
        }
      } // end hasNext()
    } // end class
    
    public class HangingScanner {
       /** Main method */
       public static void main(String[] args) {
          
          ArrayList<Integer> numbers = new ArrayList<Integer>();
          
          // Create a Scanner
          Scanner input = new Scanner(System.in);
          System.out.println("hasNext=" + CheckScanner.hasNext(input)); //<<<<<<<<<<<<<<<
          
          // Read all numbers
          while(input.hasNextInt()){
             System.out.print("Enter a number: ");
             
             // Convert string into integer
             int nxt = input.nextInt();
             System.out.println(" got " + nxt);
             numbers.add(nxt);
          }
    
          System.out.print("numbers=" + numbers);
       }
    }

  10. #10
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    Got it! I did a search in my backyard:
    Java Programming - beginers question about taking input from console

    the in.close() closes System.in, that's why the next scanner object fails, duh.

    If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.
    Last edited by PhHein; 07-08-2010 at 09:40 PM.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    Thanks for that.

  12. #12
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,429
    Rep Power
    7

    Default

    You're welcome, now we only need the OP to come back and to understand.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  13. #13
    varunb is offline Member
    Join Date
    Jul 2007
    Posts
    3
    Rep Power
    0

    Thumbs up

    Quote Originally Posted by PhHein View Post
    Got it! I did a search in my backyard:
    Java Programming - beginers question about taking input from console

    the in.close() closes System.in, that's why the next scanner object fails, duh.
    Thanks...it solved my problem. :)

Similar Threads

  1. Testing if an input is an integer
    By Mayday in forum New To Java
    Replies: 1
    Last Post: 05-08-2010, 06:14 PM
  2. Replies: 5
    Last Post: 11-26-2009, 08:01 PM
  3. how to know the input value of integer
    By ran830421 in forum New To Java
    Replies: 15
    Last Post: 11-18-2009, 10:01 PM
  4. input to an integer (simply)
    By chitwood in forum Advanced Java
    Replies: 3
    Last Post: 03-18-2009, 07:34 AM
  5. Can't get my "if" statement to read user input
    By daletron3030 in forum New To Java
    Replies: 7
    Last Post: 01-16-2009, 06:24 AM

Posting Permissions

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