Results 1 to 4 of 4
  1. #1
    BillyB is offline Member
    Join Date
    Nov 2010
    Posts
    22
    Rep Power
    0

    Default End Scanner int input with text value

    I have a Scanner object and the values being input are integers. What I would like to do is have the user enter an 's' to stop the input. I have the following code (which of course throws an error). How can I accomplish my goal? Thank you.

    int stop = 's';
    int number;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the first number of the array: ");

    number = input.nextInt();

    while (input != stop)
    {
    //process this code
    }

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    if they enter the number which is used for s it will stop. Try printing out stop
    Java Code:
    System.out.println(stop);
    Then use that number as the input, and see what happens.

    You could also use readLine and try to parse it to an integer with
    Java Code:
    Integer.parseInt(String)
    do this after testing if it's s. You can also catch any exceptions for when integer.parseint doesnt work.

  3. #3
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,836
    Rep Power
    8

    Default

    You're trying to input a String, but you're using the nextInt() function. Why? If you want to read in Strings, you have to use one of the methods that reads in Strings.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,750
    Rep Power
    19

    Default

    You're going about this backwards.
    As KevinWorkman says, if you need to read a String then read a String.

    Since an 's' is a valid input, then you'll have to read everything in as Strings, then convert them to ints if they aren't an 's'.

Similar Threads

  1. how to reverse some input from scanner
    By moncur in forum New To Java
    Replies: 24
    Last Post: 11-09-2010, 02:59 PM
  2. Replies: 2
    Last Post: 09-14-2010, 01:24 AM
  3. Changing Scanner input type
    By mlad in forum New To Java
    Replies: 13
    Last Post: 03-18-2010, 04:22 PM
  4. problem with Scanner in Getting users input
    By kliane in forum New To Java
    Replies: 8
    Last Post: 01-17-2010, 04:37 PM
  5. Scanner input problem
    By slayer_azure in forum New To Java
    Replies: 3
    Last Post: 05-26-2008, 10:49 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
  •