Keyboard input or Console Output

I'm self teaching java... I got stuck with one of the exercises that is supposed to demonstrate the basic input and output through entering data on console...
I went about writing the code as:
public class Program2 {
public static void main(final String [ ] args) {
KeyboardInput in = new KeyboardInput () ;
System.out.print ("Type your name: ") ;
It doesn't compile:((((.... it says "KeyboardInput" is not a type...
I would really appreciate if somebody could respond to this silly problem.

For keyboard input from console the program would be
public class Console{
  public static void main(String[] args){
    try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter Your Name: ");
      String name = reader.readLine();
      System.out.println("Your Name is "+name);
    }catch(Exception ex){
      ex.printStackTrace();
}

Similar Messages

  • Keyboard input from console

    I have a swing GUI application which must show content reflecting to keyboard input.
    Input must be readed from System.in. When I type anything in console it works, but when
    I switch to GUI then keyboard input doesnt go to System.in. Any ideas how to solve this problem?
    Make keyboard input go to System.in while looking the GUI?
    Thank you in advance.

    I registred JFrame as keydispatcher and everything worked fine, except the fact that every keystroke got catched in dispatchEvent() three times.
    What concept am I missing? How to get one occurance of each keyevent?

  • Keyboard Input Output Problems on Mac OS X

    Hey guys,
    I'm at college studying Java, however my teacher and the rest of the class all use the Kawa IDE, I've been using Project Builder, provided with Mac OS X. Our tutor gave us a class made up of various methods which the college designed to handle keyboard Input and Output, however when I import it I get unpredictable results. I've put it online at: http://www.lostroom.co.uk/inout/
    All I'm trying to do is run a simple program;
    import InOut;
    class CostReckoner
    public static void main(String[] args)
    // Declare the variables
    int quantity;
    double unitCost, basicCost, vatCost, totalCost;
    double vatRate = 0.175;
    // Input the number of items and the cost per item
    System.out.print("What is the unit cost of the items?");
    unitCost = InOut.readDouble();
    System.out.print("How many items in the order?");
    quantity = InOut.readInt();
    // Calculate the cost of the order
    basicCost = unitCost * quantity;
    vatCost = basicCost * vatRate;
    totalCost = basicCost + vatCost;
    //Output the total cost of the order
    System.out.println("Cost �"+InOut.format(basicCost,2));
    System.out.println("Vat �"+InOut.format(vatCost,2));
    System.out.println("Total �"+InOut.format(totalCost,2));
    I seem to need to press space bar after I input anything, as it doesn't recognise "Return" without it. Any ideas ??
    Strange thing is it seems to work fine on the PC Kawa IDE within college. Any advice you guys could offer would be really appreciated. Send me an email at: <[email protected]> if you can help.
    Regards, Gareth

    Hi thanks for your help, I tried compiling the code you gave me to read the streams, however I seem to be have problems with it.
    ERROR
    keys.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
    n=stream.read();
    HERE IS THE CODE I'M TRYING TO COMPILE
    import java.io.*;
    public class keys {
    public static void main(String[]arguments)
    BufferedInputStream stream = new BufferedInputStream(System.in);
    int n=0;
    while(true){
    n=stream.read();
    System.out.println(Integer.toHexString(n));
    if (n==0x30) break;// this termination condition is optional
    Any ideas ??

  • HttpServer error in reading buffer size via keyboard input - HELP

    I've written a simple HttpServer program that reads keyboard input to construct a buffer to copy the requested file into the socket's output stream. I've done the string-to-integer conversion using BufferedReader and parse.Int. However, when I go to use the int later in the program, I keep getting the message "variable b may not have been initialized." Can anyone tell me what's missing from the code below? Thanks.
    private static void sendBytes(FileInputStream fis, OutputStream os)throws Exception
         //Construct a buffer via console input
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         String str;
         int b;
              System.out.println("Enter desired buffer size or CTRL-C to break.");
         //Convert entry to an integer
         do
              str = br.readLine();
                 try
                   b = Integer.parseInt(str);
              catch(NumberFormatException e)
                   System.out.println("Invalid entry.");
         while((str=br.readLine())!=null);
         //Construct a buffer
         byte[] buffer = new byte;
         int bytes = 0;
         //Begin timing HTML page delivery
         long start, end;
              System.out.println("Timing for Web page delivery");
         start = System.currentTimeMillis();
         //Copy requested file into the socket's output stream
              while((bytes = fis.read(buffer)) != -1)
              os.write(buffer, 0, bytes);

    As the message suggests, what is missing is code to initialize the variable b. The first mention ("int b;") does not initialize it. The second mention ("b = Integer.parseInt(str);") only initializes it if no exception is thrown. So it's possible for b to be uninitialized when you actually try to use it.
    What do you need to change? First you need to decide what's to be done if the keyboard input isn't a valid integer. Do you have a default value in mind? If so, put that where you declare the variable ("int b = 42;"). If not, just initialize the variable to zero ("int b = 0;").

  • Simple question about systemd console output - can i get a timestamp?

    hello. with the old syslog program, sending the log to a console used to yield essentially the same output as /var/log/everything.log, critically including timestamps before each entry. Now with systemd, enabling console output just gives each entry by itself, so you can't tell if you're looking at 5 seconds worth of activity or 5 days. any way a timestamp can be added here? i'd find that useful on my servers, as I have a screen connected to them but no keyboard.
    thanks

    Console output of what? Please post the exact command you're using and the output.
    # journalctl -b
    -- Logs begin at Sun 2013-08-11 17:23:43 CEST, end at Wed 2013-09-11 05:36:39 CEST. --
    Sep 10 19:11:44 localhost systemd-journal[36]: Runtime journal is using 184.0K (max 49.8M, leaving 74.8M of free 498.4M, current limit 49.8M).
    Sep 10 19:11:44 localhost systemd-journal[36]: Runtime journal is using 188.0K (max 49.8M, leaving 74.8M of free 498.4M, current limit 49.8M).
    Sep 10 19:11:44 localhost kernel: Initializing cgroup subsys cpuset
    Sep 10 19:11:44 localhost kernel: Initializing cgroup subsys cpu
    Sep 10 19:11:44 localhost kernel: Initializing cgroup subsys cpuacct
    Sep 10 19:11:44 localhost kernel: Linux version 3.11.0-1-ARCH (tobias@testing-i686) (gcc version 4.8.1 20130725 (prerelease) (GCC) ) #1 SMP PREEMPT Tue Sep 3 0
    Sep 10 19:11:44 localhost kernel: e820: BIOS-provided physical RAM map:
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x0000000000000000-0x000000000009f7ff] usable
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x000000000009f800-0x000000000009ffff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x00000000000e0000-0x00000000000fffff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x0000000000100000-0x000000003f6effff] usable
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x000000003f6f0000-0x000000003f6fafff] ACPI data
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x000000003f6fb000-0x000000003f6fffff] ACPI NVS
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x000000003f700000-0x000000003f77ffff] usable
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x000000003f780000-0x000000003fffffff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x00000000fec00000-0x00000000fec0ffff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x00000000fee00000-0x00000000fee00fff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x00000000ff800000-0x00000000ffbfffff] reserved
    Sep 10 19:11:44 localhost kernel: BIOS-e820: [mem 0x00000000fffffc00-0x00000000ffffffff] reserved
    <cut>
    Sep 10 19:11:56 black kernel: IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
    Sep 10 19:11:56 black systemd-logind[164]: Watching system buttons on /dev/input/event2 (Power Button)
    Sep 10 19:11:56 black systemd-logind[164]: Watching system buttons on /dev/input/event1 (Power Button)
    Sep 10 19:12:00 black login[167]: pam_unix(login:session): session opened for user karol by LOGIN(uid=0)
    Sep 10 19:12:00 black systemd[1]: Starting user-1000.slice.
    Sep 10 19:12:00 black systemd[1]: Created slice user-1000.slice.
    Sep 10 19:12:00 black systemd[1]: Starting User Manager for 1000...
    Sep 10 19:12:00 black systemd-logind[164]: New session 1 of user karol.
    Sep 10 19:12:00 black systemd[1]: Starting Session 1 of user karol.
    Sep 10 19:12:00 black systemd[191]: pam_unix(systemd-shared:session): session opened for user karol by (uid=0)
    Sep 10 19:12:00 black systemd[1]: Started Session 1 of user karol.
    Sep 10 19:12:00 black login[167]: LOGIN ON tty1 BY karol
    Sep 10 19:12:00 black systemd[191]: Failed to open private bus connection: Failed to connect to socket /run/user/1000/dbus/user_bus_socket: No such file or dir
    Sep 10 19:12:00 black systemd[191]: Mounted /sys/kernel/config.
    Sep 10 19:12:01 black systemd[191]: Stopped target Sound Card.
    Sep 10 19:12:01 black systemd[191]: Starting Default.
    Sep 10 19:12:01 black systemd[191]: Reached target Default.
    Sep 10 19:12:01 black systemd[191]: Startup finished in 619ms.
    Sep 10 19:12:01 black systemd[1]: Started User Manager for 1000.
    Sep 10 19:12:00 black dhcpcd[168]: eth0: leased 192.168.1.4 for 259200 seconds
    Sep 10 19:12:00 black dhcpcd[168]: eth0: adding host route to 192.168.1.4 via 127.0.0.1
    Sep 10 19:12:00 black dhcpcd[168]: eth0: adding route to 192.168.1.0/24
    Sep 10 19:12:00 black dhcpcd[168]: eth0: adding default route via 192.168.1.1
    <cut>
    (No idea why there's 'Sep 10 19:12:01' followed by 'Sep 10 19:12:00')

  • I want to show console output in my cmd prompt in C# winform application

    Hi,
    I'm launching the some process in C# .net Winform appliaction. But i couldn't able to see console output on the screen. The process is getting launched but inside cmd prompt window, it is showing nothing. I would like to show something on cmd prompt. Please
    help on this.
     using (Process comxdcProcess = new System.Diagnostics.Process())
                            comxdcProcess.StartInfo.FileName = fileName;
                            comxdcProcess.StartInfo.Arguments = args;
                            comxdcProcess.StartInfo.RedirectStandardError = true;
                            comxdcProcess.StartInfo.RedirectStandardOutput = true;
                            comxdcProcess.StartInfo.UseShellExecute = false;
                            comxdcProcess.Start();
                            this.errorComment = comxdcProcess.StandardError.ReadToEnd();
                            StreamReader myStreamReader = comxdcProcess.StandardOutput;
                            //// Read the standard output of the spawned process. 
                            this.errorComment = myStreamReader.ReadToEnd();
                            comxdcProcess.WaitForExit();
    click "Proposed As Answer by" if this post solves your problem or "Vote As Helpful" if a post has been useful to you Happy Programming! Hari

    @Hariprasadbrk
    Do you mean you have use process class to start "cmd prompt" And want to display some output in it?
    If so, there is no need to use RedirectStandardOutput property. This property means the output of an application is written to the
    Process.StandardOutput stream.
    // Setup the process with the ProcessStartInfo class.
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = @"C:\7za.exe"; // Specify exe name not cmd exe.
    start.UseShellExecute = false;
    start.RedirectStandardOutput = true;
    // Start the process.
    using (Process process = Process.Start(start))
    // Read in all the text from the process with the StreamReader.
    using (StreamReader reader = process.StandardOutput)
    string result = reader.ReadToEnd();
    Console.Write(result);
    Output
    This section shows the output of the process.
    7-Zip (A) 4.60 beta Copyright (c) 1999-2008 Igor Pavlov 2008-08-19
    Usage: 7za <command> [<switches>...] <archive_name> [<file_names>...]
    [<@listfiles...>]
    So you can start a cmd exe.
    Please also take a look at the article from codeproject
    How to redirect Standard Input/Output of an application
    In summary, the shutdown proces is invoked from my application, and it displays the output from the process in RichTextBox control.
    Have a nice day!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to print console output

    Hi, I have a JSP page and I would like to print STDOUT to the page. Is this possible?
    I've seen a few methods and none work for me:
    BufferedReader reader = new BufferedReader(System.out);
    String input = reader.readLine();
    out.println(input);*** Error: Type BufferedReader was not found.
    FileOutputStream out;
                    PrintStream ps; // declare a print stream object
                    try {
                     // Create a new file output stream
                    out = new FileOutputStream("myfile.txt");
                            // Connect print stream to the output stream
                            ps = new PrintStream(out);
                            ps.println ("This data is written to a file:");
                System.err.println ("Write successfully");
                            ps.close();
                    catch (Exception e){
                            System.err.println ("Error in writing to file");
                    }*** Error: Duplicate declaration of local variable "out".
    *** Error: The type of the left-hand side in this assignment, "javax/servlet/jsp/JspWriter", is not compatible with the type of the right-hand side expression, "java/io/FileOutputStream".
    *** Error: No match was found for constructor "PrintStream(javax.servlet.jsp.JspWriter)".
    So what's next?
    How can I call the console without writing to a file first?
    I would like AJAX to show console output in real-time.

    Thanks for your help.
    The reason I have the script to write to a file is because it's the closest I could find to what I want. Ideally, I would be able to run a script that prints to the console but I want to grab the system.out going to the console and display it on the page.
    Basically, I want the page to act as a console but not redirect the output (I want it to still go to the console) and I don't want it in a text file that the page reads.
    So for example, the page loads and while that is occurring, the server grabs the console output and prints to the page. Then I run a function on the page that prints to the console and on the refresh, print the updated output. Ideally, I would restrict the output that was relevant to the page's functions and ignore every output to the console but I'm not (trying to be) picky.
    So how would that work?
    Pseudo-code:
    for (int i=0;i < System.out().length(); i++) {
            String grabbedtext += System.out().toString();
    }out.println(grabbedtext);

  • [Solved] Programs hang on keyboard input (uim-xim)

    Update: I've narrowed the issue down (via trial and error) to uim-xim.  If it's running, it causes this problem (in XMonad) and if it isn't, gnucash has no issues.  Oddly enough, when I start uim-xim by hand after gnucash, it works fine too.  Starting uim-xim by hand before gnucash results in the same issue, and so I'm inclined to believe it's either an issue with XIM implementation, or simply uim-xim.  Might also be a mixture of XMonad and uim-xim, as it works fine in Openbox.
    I've noticed lately that certain GTK programs (I'd list them, but I haven't paid close attention until today, where I was using gnucash) work fine until I try to input anything via the keyboard.  The moment I start typing (or, at the latest when I hit the shift key or backspace key) the program will hang (without any error message).  I originally assumed that this was an issue with the program - not my window manager.  However, I tried one of the problem programs (gnucash) in Openbox today, and it works just fine.  That leads me to assume it's caused by my configuration in some way.  I have absolutely no idea where to start debugging this issue. 
    A bit of information:
    I use UIM (in both openbox and XMonad with identical configurations), run a script for a Japanese date format in XMonad (piped to dzen), and load the same xmodmap file in both window managers.  Also, I start all my window managers using CDM (Console Display Manager), but in the case of XMonad I supply a bash script instead of the binary, in order to preload certain files.  Also, I use a german keyboard layout.
    <I removed the rest of this post because it was long and, ultimately, irrelevant>
    Last edited by lswest (2012-05-01 09:53:46)

    spectater wrote:
    Same situation, Confirmed here
    I'm having the same problem with my laptop after upgrading to  gnome 3 : 
      gnome-terminal  , gedit  can not accept  keyboard input , lower case letters, enter ,   backspace and so on ,   but  upper case letters are OK.
    files  can not be renamed with  nautilus , also the find function affected  in nautilus
    while other programs such as  xterm ,firefox  , pidgin  skype , thunar  leafpad  libreofficecan  ...and so on  work out of the box .
    lower case & upper case letters all are not accepted well in my case.

  • How to set echo of console output  as ' * ' ?

    I've made a bank application in java using console input/output and when the password is typed,it echo the same word as typed.
    So how can i change the echo of console output specially when asking for password ?

    Thankue very much.
    But do me a favour i've jdk 1.5 installed in my system.
    I don't have java.io.Console class file, so will you please send me only that class file or give me link from where i can get that.
    My email address is -
    [email protected]

  • Focus for keyboard input

    I have a VI that, when started, starts another vi that runs in a
    different part of the screen. I want the user to be able to use the
    keyboard and the original VI be the one that receives the keyboard input
    (key navigation, etc.). How do I get the focus back on the original VI
    without "clicking" on it with the mouse?
    -Stephen

    Try using Property Node under Application Control. Set the class to VI.
    Set FP.IsFrontmost to true. Wire the name of the original vi to the Open VI
    Reference function and then wire the output vi reference to the property
    node. This should return keyboard control to the original vi. If you want
    a specific control within the vi to have focus initially, right click on the
    control and create a property node. Select KeyFocus for the property,
    select Change All To Write, and wire true to the property.
    "Stephen" wrote in message
    news:[email protected]..
    > I have a VI that, when started, starts another vi that runs in a
    > different part of the screen. I want the user to be able to use the
    > keyboard and the original VI be the one that receives the key
    board input
    > (key navigation, etc.). How do I get the focus back on the original VI
    > without "clicking" on it with the mouse?
    >
    > -Stephen

  • Xmonad/Slim causing keyboard input failure on agetty?

    I have just installed xmonad along with slim, and I notice that when xmonad is running
    and i Alt+FX out to a tty console, a lot of my keyboard inputs are missed. E.g. I will try
    to type "pacman -Syu" and all i get is "pamn Su". It is not key-specific as I can
    (with repeated attempts) get the letters which were missed in that example.
    I'm pretty sure the problem isn't slim because before I've logged in, if i switch out to a
    tty i don't have the problem.
    I did notice that xmonad hasn't changed slim's background, but I think that's more
    down to the fact that I haven't told xmonad to do otherwise, rather than a possible
    cause of the problem.
    xmonad's functionality is fine, no keyboard problems there. Only when I try on agetty.
    Anyone seen this before?
    thanks
    EDIT: I suppose it has to be slim... I tried booting with runlevel 3 instead and doing
    startx manually takes away the problem. I'm not impressed enough with graphical
    login managers to pursue this any longer, i'll just start X from .bash_profile
    Still curious as to whether anyone has ever seen this before though
    Last edited by hseu (2011-04-14 16:40:41)

    Thanks for your reply, good to know it's not just me
    It is a shame though, it was nice(looking) while it lasted (about an hour).

  • Can java program simulate keyboard input?

    is it possible to create a java program or applet that simulates an end-user's keyboard input into another java applet? is it also possible to feed the output of that target applet to a file based on the different input combinations?
    and How?
    Thanks.

    Take a look at the API-docs for the class java.awt.Robot . This generates system-level input-events. Might not work in an applet, I do not know whether an applet has the right to do this.
    The second question is actually the more difficult one, since normal applets can not do file access.

  • Keyboard input not working at boot

    Hello --
    I don't get keyboard input for ~30 seconds at boot, and I'm not sure why. I'm using a hand-rolled kernel with no initrd, though when I use the stock Arch kernel with initrd it does the same thing. According to my kernel logs, the keyboard is recognized before the root filesystem is mounted (and it appears to be PS2, not USB), and from reading the rc scripts, little or nothing happens after the ttys are started.
    udev starts before the root fs is mounted, and when root is fscked at boot, I don't encounter this problem. Therefore I think udev is at fault. Via I can't find any information on telling udev to deal with the keyboard earlier.
    Any ideas on how to fix this? Other than putting "sleep 30" in my rc scripts, that is.

    Sorry, I wasn't being very clear.
    I'm using a laptop, and lsusb doesn't report anything except the buses themselves. Therefore I concluded that my keyboard is not a USB keyboard, as I mentioned above.
    This is booting to a tty console, not to X, so it can't be a KDE issue. And I have full control of my keyboard with GRUB; it's just the kernel that hesitates to acknowledge its existence.

  • Keyboard input using BufferedReader

    Trying to use BufferedReader for keyboard input, first of all is it possible? And second how do I do construct the stream?
    I am trying BufferedRead in = new BufferedReader(System.in); and this is not working .
    Please help.

    Trying to use BufferedReader for keyboard input, first
    of all is it possible? And second how do I do
    construct the stream?
    I am trying BufferedRead in = new
    BufferedReader(System.in); and this is not working .
    Please help.Try this. I got it from Core Java 1.2 Volume 1 - Fundamentals by Horstmann and Cornell:
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));To read something from the console at that point you'd do something like this:
    String inputData=in.readLine();Hope that helps.

  • Pipe console output to application

    Hello all
    Does anyone know of a quick and simple way of piping the console output to, say, a JTextArea in my application? I have imported a 3rd-party library into my app which, when DEBUG=true, outputs to the console via (I suppose) System.out.println(). I want to intercept that stream and output that directly in my app.
    Ideas?
    Thanks in advance
    HK

    You can use System.setOut (and System.setErr or System.setIn) to choose different default standard input/output/error streams.
    So assuming this app is using System.out, you could just remap that to something that prints to a JTextArea.

Maybe you are looking for