Question about reading a string or integer at the command line.

Now I know java doesn't have something like scanf/readln buillt into it, but I was wondering what's the easiest, and what's the most robust way to add this functionality? (This may require two separate answers, sorry).
The reason I ask is because I've been learning java via self study for the SCJA, and last night was the first time I ever attempted to do this and it was just hellish. I was trying to make a simple guessing game at the command line, I didn't realize there wasn't a command read keyboard input.
After fighting with the code for an hour trying to figure it out, I finally got it to read the line via a buffered reader and InputStreamReader(System.in), and ran a try block that threw an exception. Then I just used parseInt to get the integer value for the guess.
Another question: To take command line input, do you have to throw an exception? And is there an easier way to make this work? It seems awfully complicated to take user input without a jframe and calling swing.
Edited by: JGannon on Nov 1, 2007 2:09 PM

1. Does scanner still work in JDK1.6?Try it and see. (Hint: the 1.6 documentation for the class says "Since: 1.5")
If you get behaviour that doesn't fit with what you expect it to do, post your code and a description of our expectations.
2. Are scanner and console essentially the same thing?No.
Scanner is a class that provides methods to break up its input into pieces and return them as strings and primitive values. The input can be a variety of things: File InputStream, String etc (see the Scanner constructor documentation). The emphasis is on the scanning methods, not the input source.
Console, on the other hand, is for working with ... the console. What the "console" is (and whether it is anything) depends on the JVM. It doesn't provide a lot of functionality (although the "masked" password input can't be obtained easily any other way). In terms of your task it will provide a reader associated with the console from which you can create a BufferedReader and proceed as you are at the moment. The emphasis with this class is the particular input source (and output destination), not the scanning.
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
http://java.sun.com/javase/6/docs/api/java/io/Console.html

Similar Messages

  • Question about email setting: how  do i change the setting so i need to login to check my email. Currently it automatically come to the inbox without the need to log in. Thanks

    Question about email setting: how  do i change the setting so i need to login to check my email. Currently it automatically come to the inbox without the need to log in.

    You don't. Email comes in either by push or when you invoke the email app. Ther is no password except when you first set up the account. If your iPad is not being used as your personal device and you need to shield emails from other users, then don't use the email app.  Instead, use web mail if available from your provider.

  • I have a question about extracting pages.  When I do the function, adobe saves the individual files as " file name space page number ", so the files look like this "filename 1.pdf", "filename 2.pdf", "filename 3.pdf".  Without too many gory details, I a

    I have a question about extracting pages.  When I do the function, adobe saves the individual files as "<file name><space><page number>", so the files look like this "filename 1.pdf", "filename 2.pdf", "filename 3.pdf".  Without too many gory details, I am using excel to concatenate some data to dynamically build a hyperlink to these extraced files.  It casues me problems, however, for the space to be the the file name.  Is there any way to change the default behavoir of this function to perhaps use a dash or underscore instead of a space?

    No, you can't change the default naming scheme. You can do it yourself if you extract the pages using a script instead of using the built-in command.

  • Hello am using ios 7.0.4 I have a question about messages that it does not show the time of a particular message after first message that I recive form a paricular person so please in the next version change this and with every message show time and date

    hello am using ios 7.0.4 I have a question about messages that it does not show the time of a particular message after first message that I recive form a paricular person so please in the next version change this and with every message show time and date

    Hi,
    How is everything going? Have you checked this issue from OWA? If so, please let me know the result.
    In adition, please also try to use the following powershell commands to check if the assistant has right permissions:
    Get-MailboxFolderPermission -Identity
    CEO’s email address:\Calendar -User assistant’s email address
    Also check with:
    Get-Mailbox -Identity CEO’s mailbox
    | fl *GrantSendOnBehalfTo
    Please let me know the result.
    Best Regards,
    Steve Fan
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click
    here

  • HT201303 i have tried to perchase a movie and it keeps coming up with questions about my past thet i dont remember the answer to. how do i find out the answers? i have never come across these questions until now

    i have tried to perchase a movie and it keeps coming up with questions about my past thet i dont remember the answer to. how do i find out the answers? i have never come across these questions until now

    Contact iTunes Customer Service and request assistance
    Use this Link  >  Apple  Support  iTunes Store  Contact

  • Problem - reading an abitrary string from the command line in basic swing

    Hi,
    I'm sorry if this problem is a bit basic, but I've only just started swing in Java. Anyway, I'm trying to adapt a basic swing version of the HelloWorld class. When I try to pass an abitrary string from the command line to the label within the class, I get the following error,
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
            at week2.HelloWorldSwing_commandline.main(HelloWorldSwing_commandline.java:31)
    Java Result: 1I must be missing something because I can't see where the problem is in the following code.
    import javax.swing.*;
    import java.awt.*;
    public class HelloWorldSwing_commandline {
        String message;
        private static void createAndShowGui(String message){
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JLabel label = new JLabel(message);
            Container content = frame.getContentPane();
            content.add(label);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[ ] args) {
         createAndShowGui(args[1]);
    }Any help would really be appreciated.

    Hi,
    I've tried changing the index value to O in the main method, but I still get the same error.
    I'm running this in NetBeans 4.1, and when I try to run the class I get the error as listed above.
    Any ideas how to correct this error?
    Thanks

  • Reading commands from the command line

    Ok I've read quite a bit about streams, and I get the gist that you are suppose to open up a "stream," whether it from a file or from something else, and then you have to do all sorts of stuff to it like activate it or something, or whatever. But all I want to do is take an input from the command line, for example my name, and have it output "Hi [name]." I could swear I've done this before with a simple command like
    System.in.read() or something like that, but I read up on it and read is not a method that does that? So how does one just do a simple command line input into a variable...for what I want to do is control movement on a maze. If somebody can direct me to some documentation I would be happy as well. Thank you

    btw - "deadseasquirrels" - like the name. Have another program;-
    import java.io.*;
    import java.util.Random;
    public class Do_Writing {
       public static void main( String args[] ) throws IOException {
       BufferedReader in = new BufferedReader
                           (new InputStreamReader(System.in));
       Random rand = new Random();
       int i = 1+ rand.nextInt(10);
       String s1;
       System.out.println("Guess a number between 1 and 10");
          try {
             while ((s1 = in.readLine() ) != null) {
                // if( ... I'll leave the rest to you to figure out
                // when they get it right don't forget to include;-
                System.exit(0);
                in.close();
       catch (IOException ignore) { }                     
    }

  • Want to learn more about the command line for Mac OS X

    Hi, I'm kind of new here...I've been using my MacBook since last summer, however I want to really get a feel of the command line and would like some recommendations on how to learn more about it.
    Looks like it is based off of BSD, and I've been using Linux for about 10 years now and also have a CompTIA Linux+ cert, however some of the commands aren't the same.
    So, if anyone can post some websites/recommendations that would be great.
    thanks

    Buy any one or more of the many books available at Amazon.com about Unix under OS X. Linux and Unix are related but not the same. Even FreeBSD Unix is not the same as what's implemented under the OS X hood.
    And you will find other good books at PeachPit.com.
    There also is a separate Unix forum here.

  • Connection string not in the command line argument.

    Hi,
    I found myself constantly looking for the debug connection string and to enter it in the "Command line arguments".  I decided to create my Add-On base class from which all my add-ons inherit from.
    In the constructor of the base Add-On class I determine the connection string based on whether the code is in debug more or not.
    Example:
    string connectionString  = string.Empty;
    #if DEBUG
        _connectionString = "0030002C0030002C00530041005000420044005F00440061007400650076002C0050004C006F006D0056004900490056";
    #else
        // Get the log info
        if (Environment.GetCommandLineArgs().Length > 1 )
            _connectionString = Environment.GetCommandLineArgs().GetValue(1).ToString();
    #endif
    I hope this help.
    Edited by: B1Computing on Apr 5, 2011 8:20 PM

    Hi,
    I found myself constantly looking for the debug connection string and to enter it in the "Command line arguments".  I decided to create my Add-On base class from which all my add-ons inherit from.
    In the constructor of the base Add-On class I determine the connection string based on whether the code is in debug more or not.
    Example:
    string connectionString  = string.Empty;
    #if DEBUG
        _connectionString = "0030002C0030002C00530041005000420044005F00440061007400650076002C0050004C006F006D0056004900490056";
    #else
        // Get the log info
        if (Environment.GetCommandLineArgs().Length > 1 )
            _connectionString = Environment.GetCommandLineArgs().GetValue(1).ToString();
    #endif
    I hope this help.
    Edited by: B1Computing on Apr 5, 2011 8:20 PM

  • How do I execute a returned sql string from a function on the command line?

    Hi,
    I have written a pl/sql function that will dynamically create a sql select statement. I need to be able to execute this statement from the command line. e.g from sqlplus
    Say my function is called "sql_create" and it returns "select * from customer"
    How do I execute the returned value from the command line?" Is it possible?
    SQL> select sql_create from dual;
    SQL_CREATE
    select * from customer
    SQL>
    So I try:
    SQL> exec execute immediate 'select sql_create from dual';
    SQL>
    I don't get an error but I don't get the result set either.
    Is there a command I can use instead of execute immediate?
    thanks,
    Susan
    Edited by: Susan123456 on Jul 2, 2009 1:21 AM

    depends on the frontend. Most frontends (like Java and .Net) know how to handle REF CURSORS. Instead of returing a "string" which represents a query, return a ref cursor
    SQL> ed
    Wrote file afiedt.buf
      1  create function sql_q return sys_refcursor
      2  is
      3     rc sys_refcursor;
      4  begin
      5     open rc for select * from emp;
      6     return rc;
      7* end;
    SQL> /
    Function created.
    SQL> var r refcursor
    SQL>
    SQL> exec :r := sql_q
    PL/SQL procedure successfully completed.
    SQL> print r
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        900                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-81       1700        300         30
          7521 WARD       SALESMAN        7698 22-FEB-81       1350        500         30
          7566 JONES      MANAGER         7839 02-APR-81       3075                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1350       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-81       2950                    30
          7782 CLARK      MANAGER         7934 09-JUN-81       2551                    10
          7788 SCOTT      ANALYST         7566 19-APR-87       3100                    20
          7839 KING       PRESIDENT            17-NOV-81       5100                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       1600          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87       1200                    20
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7900 JAMES      CLERK           7698 03-DEC-81       1050                    30
          7902 FORD       ANALYST         7566 03-DEC-81       3100                    20
          7934 MILLER     CLERK           7782 23-JAN-82       1400                    10

  • Dumb question- how do I get to the command line without X running?

    Hi,
    As per the title please... I need to rerun Xorg -configure, but cannot for the life of me figure out how to shut down X and get to a command line
    Thanks

    Bes wrote:
    Ctl alt and backspace just takes me out to the login screen.. from there I can't get to the terminal without X running.
    Ctrl Alt F5 gets me to the command line, but I can't kill the X server
    Thanks though
    so with ctrl+alt+f5 you're at the console
    log in if you need to, then
    ps ax | grep gdm
    4441 ? Ss 0:00 /usr/sbin/gdm-binary
    4442 ? S 0:00 /usr/sbin/gdm-binary
    4444 tty7 SLs+ 3:38 /usr/bin/Xorg :0 -audit 0 -auth /var/lib/gdm/:0.Xauth
    6633 pts/0 S+ 0:00 grep gdm
    kill 4444
    the above example assumes gdm is your login manager so substitute whatever you're using, and you can kill the other instances of gdm (in my example processes 4441 and 4442 but don't waste your time on the grep process 6633
    now redo your X config
    (actually you could run this from a terminal from within X and it should have the same effect of dropping you back to console
    Last edited by tj (2008-04-20 09:36:15)

  • A question about reading tomcat source code

    Hi, everyone!
    I just saw the tomcat source code, there is a method named "await" in StandardServer class. The comment of this method decribe that this method will wait util a proper shutdown command is received.
    I'm confused about it after read this method.
    In my opinion, this method create a server socket on port 8005 by default, and wait for "SHUTDOWN" string to only close the server socket which is listening on port 8005.
    But I think this method is supposed to close all the server sockets which are listenning for client's request and belong to this server when port 8005 received "SHUTDOWN" string.
    Thank you in advance.
    Edited by: Garrett.Li on Oct 17, 2007 9:18 AM

    about reading tomcat source code i cant get you man,

  • Question about reading hex data

    Hello! I am a Labview Novice and having a problem about reading hex data.
    Basically I am having bytes from the serial port like this: "80100E0E0AB4F646F24A00911267087E032080057FFF "
    It is not encoded in ASCII. What I want to do is to convert the hex to an ASCII hex string.
    so that the string would become hex numbers in ASCII.
    I think the following might be a solution, but I have no idea what the subvi is in the solution.
    http://forums.ni.com/t5/LabVIEW/Hex-String-to-Ascii-Hex-String/m-p/886078/highlight/true#M400462
    Thanks in advance and I appreciate your kind help!
    Solved!
    Go to Solution.

    coolmatthew wrote:
    What I want to do is actually this.
    You are using way too much code for all this. All you need is a concatenate strings, replacing your entire loop and such. Same result.
    (see also)
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    HEXTwiddler.png ‏4 KB

  • Question about Reader DRM activation

    Hi All
    I got a paper "FAQ ACS Discontinuation of Sales, November 30, 2004"
    I have a question about ACS.
    As I konw, ACS is discontinued effective November 30, 2004.
    and I read a section in paper below:
    Q. Will Adobe Reader and Acrobat users get support from Adobe for eBook issues?
    A. Support is not available for the free Adobe Reader, however, assistance for user activation is
    available until December 31, 2006.
    Does it mean Reader activation service will be stop until December 31, 2006?
    That's a big problem for our ebook service!!

    Adobe communicated in January to ACS customers that the DRM Activator service would remain operational until December 31, 2007, one year longer than previously announced.
    If you didn't receive this announcement, send your contact info (email and surface mail) to "[email protected]".
    You'll receive an autotmated reply that your email bounced but it will then be manually confirmed.

  • Question about read method of InputStream

    Hello everyone,
    I am using read method of InputStream to read a stream from a remote machine. The network connection is not very stable (for example, a wireless network whose the signal strength is relatively low). I am wondering if read method returns -1 (which indicates the end of the stream has been reached), and if I invoke read method again on the same stream, is it possible to read any more data?
    I think maybe I can read some more data even if read returns -1 in one time because the connection is not very stable. I am looking for your comments to my problem in my specific situation.
    regards,
    George

    Thanks Adeodatus,
    Doc says This method blocks until input data is
    available, the end of the stream is detected, or
    an
    exception is thrown.
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputS
    tream.html#read()
    I have not found any related parts in documents.
    http://java.sun.com/j2se/1.4.2/docs/api/
    Them's docs.
    if you're using a different version of java, replace
    the underlined portion with your version number.I am using JDK 1.3, and I have found related documents. But I can not find out where can I set timeout value of read operation. I am reading data from an HTTP InputStream. Can you help?
    regards,
    George

Maybe you are looking for

  • CFMPriv_PrintCore error

    Hello - I keep getting a CFMPriv_PrintCore error when certain applications try to load. I can't run these apps and I can't re-install them either - I keep getting the same error message. I have repaired Permissions and have rebuilt my directory w/ Di

  • Oracle query sort by case sensitive

    Hi All, I am using oracle database 11g. My use case is I do have a table with following values Table name -test product id     productsortdescription H58098        ACETAMIDOHYDROXYPHENYLTHIAZOLE 043994         Alloy .MM.INTHICK My query is select * f

  • Analyzing video 0%?

    I have  captured about 30 min of video through firewire 800 from a Sony Fx1 (so from tape). I chose to analize video for poeple and consolidate results. In the last two hours, backgroung tasks have done nothing. I am running final cut x  on a new mac

  • How to order a query, in design mode?

    Hi, I work with the bex 3.x and I need to know how can I order a query by a ratio/s in the design mode (with the query designer)? Before running the query. Can anybody help me? Thanks in advance. Regards.

  • After 10.5.7 update, extremely slow home sync

    After updating the server to 10.5.7, the 'full' sync at login/logout has become extremely slow. On a sub-spec Leopard machine like a 500MHz G4 it actually took 30 minutes to log in because of slow syncing. On a MacBook (Core Duo) it takes 15 minutes.