Reading one character from System.in

Is it possible to read just a single character from System.in without the user having to hit "Enter" to accept the character?
Thanks.

Is it possible to read just a single character from
System.in without the user having to hit "Enter" to
accept the character?
Thanks.No, System.in is a stream which only gets things put into it when the user hits Enter. If you want to directly interact with the keyboard (not System.in), then you need a GUI-type of app, or use a 3rd-party API such as you could find if you searched the internet for "java curses".

Similar Messages

  • Reading one character at a time

    Hello
    How can i read one character at a time from standard input (System.in) ?
    I have tried to use
    ir=new InputStreamReader(System.in)
    ir.read().
    But this method blocks until it gets a return key pressed before going forward
    Any other solution?

    public static char readChar() {
    int ch;
    char r = '\0';
    boolean done = false;
    while (!done) {
    try {
    ch = System.in.read();
    r = (char) ch;
    if (r == '\r') {
    System.out.println("Not a character. Please try again!");
    System.in.skip(1);
    done = false;
    } else {
    System.in.skip(2);
    done = true;
    } catch (java.io.IOException e) {
    done = true;
    return r;
    Try this as an method and then use it..
    This code will read will be in response untill you hit the return key but will take only the first character....

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Question on reading one character at a time.

    Hi. I am assigned a program where I have to read a series of bits (for example: 01010101). Using this I have to make a "graph out of it". The way I am supposed to make a graph is as follows:
    Each bit interval will be represented in the output as a field taht is two characters wide.
    The value of the signal is represented using either + (to represent +voltage) or - (to represent - voltage) and is always the second character in the output field.
    The first character in the output field is either:
    ' . ' = to indicate no change from the previous signal value or
    ' / ' = to indicate a negative to positive transition or else
    ' \ ' = to indicate a positive to negative transition
    Example for input: 01010101 and the output would be . + \ - . - / + \ - . - / + . + \ - / +
    The code that I got so far is that I read the input from the command line as a argument which I know is nothing but I would just like to know how to read the character one by one and make a graph which is totally boggling my mind because I have no idea how I can do it. Thank you for your help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Encoder
         public static void main(String[] args)
              int b = Integer.parseInt(args[0].trim());
              System.out.println("You spit out --> "+b);

    Alright I sorta got what you were sayin'. The code that I have now is:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Encoder
         public static void main(String[] args)
              String toEncode = String.valueOf(args[0]);
              StringBuffer result = new StringBuffer();
              char lastChar = toEncode.charAt(0);
              char curChar = '0';
              char lastSign = '+';
              int length = toEncode.length();
              for (int i = 0; i < length; i++)
              curChar = toEncode.charAt(i);
              if (curChar != lastChar)
              if (curChar == '0')
              result.append("\\-");
              lastSign = '-';
              else
              result.append("/+");
              lastSign = '+';
              lastChar = curChar;
              else
              result.append(".");
              result.append(lastSign);
              System.out.println("You spit out --> "+result);
    But it doens't work according to what I want it to do. What I need it to do is the following: Lets say we have the input of 01010101, the result we will get is ". + \ - . - / + \ - . - / + . + \ - / +". The reason for this is because of the following: The graph starts on the v all the time. When there is a 0 bit there is no change and when there is a 1 bit there is an inversion of the voltage level so since we started with a 0 bit at v, when we hit 1 bit we would make a inversion to -v and when we hit 0 bit there would be no change. I don't know of what I said is clear to you or not. For this program, what it does for the input of 01010101, the output is
    " . + / + \ - / + \ - / + \ - / + ". Thank you very much.

  • Problem --serial port reading one character at a time

    Hi Friend,
    I reading the serial port  one character at a time ,  i specified it in the "serial bytes to read" option in serial port read examples.
    The problem is ----------i can able to read  the data.
    but only the first character is reading again and again...and "reading string indicator" in the serial port example shows only the first character sent ..only for a single time.since i am reading continously ----aleast the first character should display as many times i running the program
    (i am running the vi by run continous option..........)..
    please help me ....how to read the character one by one.....
    regards
    rajasekar

    Hi jason...
    I can able to read the serial port by 1 byte or 2 byte or 4 byte as i can specify it in the serial port read bytes option..(in visa serial read)..
    I need to acquire 4 bytes of data and pass it to the Math-script node..and save these 4bytes of data in array (1 row and 4 column)..
    And split this array(just like array-indexing.vi) and processing it each each column separately....
    or suggest some method to achieve my task.....please.
    one more thing the math-script node is placed in a while loop.....in order to read sequence of bytes continously.......
    regards
    rajasekar

  • How to handle multiple threads to read one line from a file each time?

    Dear Sir or Madam,
    I'm new to multiple threads java programming. What I want to do is as following:
    1. I'm writing a program to read one line of text from a very large file, and then do some process on this one line of text, then read the next line of text from this file, then process on this line of text, ...... When reach the end of the file, close the file.
    This is a single thread scenario.
    2. To fullly untilized computer resource, I want to create multiple threads to process this large file.
    One thing is very important is that each line of text in the large file has to be read sequentially. This means that the first line of text in the large file is read first, then the second line, then the third line ......
    My question is that if I create multiple threads to process the same file, how can I make sure that different threads will read the line of text from the same file sequentially?
    I don't have enough experience on java multiple threads programming, so it will be very appreaciated if you can help me on this as soon as you are available.
    Thanks and regards,
    Steven Wu

    A better solutoin would be to have a single thread that reads each line an puts it into a queue, and then multiple threads reading from the queue to process these lines.
    This will only be effective if the amount of processing to be done on each line is very large compared to how long it takes to read the line, or if you have more than one CPU on your machine.

  • When I read a (�) character  from a file, I got a �

    Hi,
    First of all Thanks in advace,
    I have a program that reads a txt file and display a page on html page, everything works well, but when a read a '�' character a got a �, I know that � = 0x241.
    My problem comes up when I try to validate each character in the file, because the program read the � character as char 0x177.
    how I can implement the comparation command , to identify if the character that was readed is a � character ?
    Any help will be appreciate.
    Thanks Again.

    Hi and thanks for you answer.
    I have a line like this :
    String Line = "CU-578355566-sue�o-dasdjhghhh";
    char[] charInLine = Line.toCharArray();
    // Here I start the validation :
    int numOfChar = Line.length;
    for ( int i =0; i < numOfChar; i++) {
    if (charInLine[i] =='�') {
    System.out.println ( "Invalid Character");
    I tried with :
    if (charInLine[i] =='�')
    if (charInLine[i] == '\u00f1')
    if (charInLine[i] ==( (char) 241)
    But Nothing works, but if I use :
    if (charInLine[i] == ( ( char) 177) it works, but this code is for �.
    Thanks!
    Postscript : It works in my machine, but not over internet.

  • Read ONE email from INBOX.

    I have a method that bring all the messages from the inbox and displays its subject on a JSP. I need that when a user click on one mail another JSP displays the full email but I don't know how to get only the SELECTED email.
    How do you select ONE mail from the Inbox ???
    Any examples ?
    Thanks.
    Eli

    I have my code on my home workstation.. so no examples right now.. but the answer to your question is yes you can.. it is possible to reference the emails in an inbox using in interger...
    int mCount = folder.getMessageCount();
         if (mCount < 1 ) {
         // no new mail
         } else {
         // insert processing code here
         Message message = folder.getMessage(1);
                    // this line above gets only the first message aka the newest in the inboxhence you can specify to get the first. or message(1);
    (guess i lied about no examples :) )
    j.

  • WSDL Error : Difficult in reading one record from server

    Hi,
    I have an issue with WSDL. i have imported the wsdl and getting the results in flex. Now when i am trying to import only one record from wsdl its throwing an error. Please any help is appreciable.
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at Components::References/ResultHandler()[E:\Project_Modified\05_10_2010\LawPadPDA\src\Compo nents\References.mxml:87]
        at Components::References/__lawPadServicesDAOPort_result()[E:\Project_Modified\05_10_2010\La wPadPDA\src\Components\References.mxml:19]
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at com.adobe.fiber.services.wrapper::AbstractServiceWrapper/http://www.adobe.com/2008/flex/model/internal::propagateEvents()[C:\depot\DataServices\bra nches\lcds_modeler101\frameworks\projects\fiber-swc\src\com\adobe\fiber\services\wrapper\A bstractServiceWrapper.as:200]
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at mx.rpc::AbstractService/dispatchEvent()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\A bstractService.as:333]
        at mx.rpc.soap.mxml::WebService/dispatchEvent()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\ rpc\soap\mxml\WebService.as:267]
        at mx.rpc::AbstractOperation/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[E:\dev\4.0.0\frameworks\pro jects\rpc\src\mx\rpc\AbstractOperation.as:254]
        at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[E:\dev\4.0.0\frameworks\projec ts\rpc\src\mx\rpc\AbstractInvoker.as:318]
        at mx.rpc::Responder/result()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\Responder.as:5 6]
        at mx.rpc::AsyncRequest/acknowledge()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\rpc\AsyncR equest.as:84]
        at DirectHTTPMessageResponder/completeHandler()[E:\dev\4.0.0\frameworks\projects\rpc\src\mx\ messaging\channels\DirectHTTPChannel.as:446]
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at flash.net::URLLoader/onComplete()
    Thanks and Regards,
    Pradeep

    The Flex forum is here:
    http://forums.adobe.com/community/flex
    This one is just for discussions on the forums themselves.

  • Read a character from a file

    Hi guys
    I have a .txt file. In that file the data are stored like "$341ACF12341ACF12341ACF12341ACF12341" now I want to read the next 128 bytes after that "$" character ??
    How to execute that??
    Thanks in advance
    Niladri
    Solved!
    Go to Solution.

    hi Newbee_3,
                                 Hope this attached image will help you. If not than let me know.
    Thanks
    Ranjeet
    Kudos are always welcome if you got solution to some extent.
    I need my difficulties because they are necessary to enjoy my success.
    --Ranjeet
    Attachments:
    Text data in string.jpg ‏31 KB

  • How do I read a character and advance the scanner to the next one?

    Hi,
    I'm writing a lexical and grammar analyzer and I don't usually program in Java. I have a method that reads one character and then parses it. The problem is that it keeps reading the same character over and over again, so my program gets stuck in an infinite loop.
    How do I make it so that BufferedReader advances to the next character in the string?
    Here is the code so far:
    public static void getChar()
                throws FileNotFoundException, UnsupportedEncodingException, IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader
                    (new FileInputStream(inputFileName), Charset.forName("UTF-8")));
            int c;
            if ((c = reader.read()) != -1){
                if (c != 32)
                    nextChar = (char) c;
                if (Character.isLetter(nextChar))
                    charClass = LETTER;
                else if (Character.isDigit(nextChar))
                    charClass = DIGIT;
                else
                    charClass = UNKNOWN;
            else{
                charClass = EOF;
                //System.out.println("Next Token is: RES_WORD. Next lexeme is: EOF.");
        } //end getChar.At first I just had a while loop, but I want this method to be called from another method and so I didn't think the while loop worked. Is there a better way?
    Help is much appreciated.
    EDIT: By the way, I don't want to read tokens. I need it to be characters. And it doesn't have to be BufferedReader. I'm open to suggestions.
    EDIT2: While I don't want to read tokens, if it's the simplest way then I'm open to it. The scanner class would work for that I guess, but then I would have to do a charAt stuff. I'm open to your insight.
    Edited by: RommelR on Feb 25, 2010 8:39 AM
    Edited by: RommelR on Feb 25, 2010 9:00 AM

    DrClap wrote:
    Every time you call that method, you open a new BufferedReader on the file and read the first character from it. So yes, you always get the same character. Solution: Don't open the BufferedReader in that method. Open it somewhere else, just once, and use it in that method.Thanks. That was stupid of me.

  • Reading a string one character at a time

    Hi,
    I'm hoping you use SmallBasic for year 10 exam students at my school.  But, I have found a problem I cannot solve.
    I need to be able to read one character at a time from a string (txt file) and convert each char to its ACSII code.
    How do to I read one char at a time from a string to enable processing?
    Thanks for your help.
    Baz 

    Here is an over the top solution that will display the Hex value of the character codes of every character in the file.
    TextWindow.Write("Enter full file name: ")
    filnam = TextWindow.Read()
    contents = File.ReadContents(filnam) 'read the entire file
    TextWindow.Clear()
    TextWindow.WriteLine("File Name: " + filnam)
    TextWindow.WriteLine("Offset: 0")
    col = 0
    row = 5
    TextWindow.CursorLeft = col
    TextWindow.CursorTop = row
    For i= 1 To Text.GetLength(contents)
    ch = Text.GetSubText(contents, i,1)
    chVal = Text.GetCharacterCode(ch)
    ConvertToHex()
    TextWindow.CursorLeft = col
    If chVal < 32 Then
    TextWindow.Write(".")
    Else
    TextWindow.Write(ch)
    EndIf
    TextWindow.CursorLeft = 20 + 2 + (col * 3)
    TextWindow.Write(Text.GetSubText(hexstr,1,2))
    col = col + 1
    If col = 8 Then
    col = col + 1
    EndIf
    If col > 16 Then
    col = 0
    row = row + 1
    If row > 20 then
    TextWindow.CursorTop = 23
    TextWindow.CursorLeft = 25
    TextWindow.Write("< < < Press ENTER to Continue > > >")
    TextWindow.Read()
    TextWindow.Clear()
    TextWindow.WriteLine("File Name: " + filnam)
    TextWindow.WriteLine("Offset: " + i)
    row = 5
    EndIf
    TextWindow.CursorTop = row
    EndIf
    EndFor
    TextWindow.WriteLine("")
    TextWindow.WriteLine("")
    Sub ConvertToHex
    HexValue[0] = "0"
    HexValue[1] = "1"
    HexValue[2] = "2"
    HexValue[3] = "3"
    HexValue[4] = "4"
    HexValue[5] = "5"
    HexValue[6] = "6"
    HexValue[7] = "7"
    HexValue[8] = "8"
    HexValue[9] = "9"
    HexValue[11] = "A"
    HexValue[12] = "B"
    HexValue[13] = "C"
    HexValue[14] = "D"
    HexValue[15] = "E"
    val = chVal
    hexstr = "h" 'Need to force Small basic to concatenate rather than add
    While val > 0
    hexPos = Math.Remainder(val, 16)
    hexstr = HexValue[hexPos] + hexstr
    val = Math.Floor(val / 16)
    EndWhile
    For hi = Text.GetLength(hexstr) To 2
    hexstr = "0" + hexstr
    EndFor
    EndSub
    Enjoy!

  • Read a character without enter

    I need to read a character from the keyboard , but I want it read without hitting <enter> to start the reading;
    the system should be waiting for for a key to be hit, and right after the hitting it should know which key it was;
    it's absolutely important that the <enter> is not hit to start the reading process
    also the solution should be as simple as possible, i.e. without any graphics or stuff like that; my program is only using the command line
    can anybody help me?
    pratajev

    use the KeyListener
    Method Summary
    void keyPressed(KeyEvent e)
    Invoked when a key has been pressed.
    void keyReleased(KeyEvent e)
    Invoked when a key has been released.
    void keyTyped(KeyEvent e)
    Invoked when a key has been typed.
    and then treat it with the
    KeyEvent.getKeyChar() method

  • GREP - search for anything except one character

    Trying to figure out if I can say this in GREP or not....
    I want to search for any character that's in a Superscript character style except for registration-mark symbols.  Is there a way to exclude one character from a search?
    Thanks, Phyllis

    Absolutely. Remember the '^' character that indicates 'start of paragraph'? Well ... apparently whoever devised GREP ran out of useful characters, because it's used again in the "exclude" group. It works like this:
    [0-9fuzzy]
    looks for a single character out of the set '0' to '9' (inclusive), 'f', 'u', 'z', or 'y'. Throwing in the hat reverses the query:
    [^0-9fuzzy]
    looks for any old single character except those in the set.
    The Registered mark has a shortcut of its own in the regular Find -- ^r -- so presumably it's "~r" in GREP mode. If not, copy-and-paste one from your text. So your GREP search should be (with Superscript formatting)
    [^~r]
    This marks only the next non-registered character; to find longer strings you can safely use
    [^~r]+
    -- which translates into "any string in superscript, one character or longer, and not containing the Registered mark". Yes, the short version is a bit easier to type.

  • How to get only one character

    my problem is the following:
    i want to get only ONE character from the input without pressing the "enter"-key. for example pressing ESC and doing something because it is ESC hit.
    thank you

    You can't. Either use a GUI or create a JNI DLL function that calls getch ().
    Kind regards,
      Levi

Maybe you are looking for

  • Help need in Drag and drop the Lines and rectangle in applet

    hi i want to create a simple paint applictaion which is capable of draw lines, rectangle, images etc. after that lines and other thinks can be moveable and rotate and scaling also. the major restrictions in its implemented only in jdk1.1. so if you p

  • HT201210 error 16, and cannot restore or update, plz help.

    my update was stopped in the middle, and next time i tried to restore and update, i cannot do any thing now, the error code (16) apprear all the times, my network, cable, windows, security, every thing is fine, plz help.

  • Caluclate time for insertion

    hi , Heads up : oracle 10g I have insert SQL script for insertion into table , It takes long time to insert into table. I have tried loading by disable indexes , but some how want to discard that process and want to narrow down on how a batch of 100

  • PLSQL sample for searching a file name in the server

    Hello All, what plsql package i need to use or any plsql sample code available for searching a file name in the server. For example If I provide any text "XX%", the plsql code should provide me the list of file names in a specific folder in server. I

  • BEx Template to Execute Queries in 7.X

    Hi , I want to create a BEx Template, So that when we execute queries in the BEx Analyzer, the Query output should come in the BEx Template with Company Logo. Can you advise, how to create a BEx Templete in BW 7.X. In 3.X, we just open a spreadsheet