Saturday, March 12, 2005

How to read a String from the keyboard

Introduction

You may want to enter text from the keyboard, do something with the text, and then print the result out to the screen. This is how to implement the application in Java:

Discussion

import java.io.*;

public class Keyboard {
    public static void main(String[] args) throws IOException {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter first number: ");
        int a = Integer.parseInt(stdin.readLine());

        System.out.println("Enter second number: ");
        int b = Integer.parseInt(stdin.readLine());

        System.out.println(a + " + " + b + " = " + (a + b));
    }    
}

No comments: