Link to home
Start Free TrialLog in
Avatar of liamgannon
liamgannon

asked on

Basic Text Input

For some very easy pints could someone tell me what the basic command is to read text entered and put it in a variable.
ie when i print out

System.out.println("Enter subject name: ");

I want to put it in a string variable called subject. How do I read it into the variable? Pathetically simple i know but it's wreckin my head and i can't find any question as simple as this on the website anywhere. Thanks
Avatar of imladris
imladris
Flag of Canada image

You can use System.in and do a read to get an array of bytes, and then convert that to a string:

byte chars[]=new byte[250];
int num=System.in.read(chars);
String input=new String(chars,0,num);
Avatar of applekanna
applekanna

an example code


*******
import java.io.*;


    public class ReadKeys {


        public String readKeys() {
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        System.out.print(": ");
        String name = null;


            try {
            name = console.readLine();
        }


            catch (IOException e) {
            name = "<" + e + ">";
        }
        return name;
    }


        public static void main(String[] args) {
        ReadKeys obj = new ReadKeys();
        System.out.println("You entered '" + obj.readKeys() + "'");
    }
}
*******

Source
http://www.planet-source-code.com/
Avatar of liamgannon

ASKER

Is there no simpler way of reading in like readline() or something similar of just one line?
isnt this what you were asking? ;)

name = console.readLine();
I thought that there was something simpler than a buffered reader, something just on one line that works the same way as println. The way that you suggested will work but i wanted something simpler that does't require a new class or a buffered reader. Is there no basic io api or somethin?
Surely there must be a simpler way of reading in without having to use a try and catch block each time
AFAIK this is as small the programm can get

import java.io.*;

    public class ReadKeys1 {

        public static void main(String[] args)  throws IOException{
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
 System.out.print("Enter text for subject :" );
        String subject = null;
        subject = console.readLine();
        System.out.println("You entered '" + subject + "'");
    }
}
ASKER CERTIFIED SOLUTION
Avatar of applekanna
applekanna

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
cooment for Complete Reference for java by Herbert Schildt and patrick naughton

"Java does not have a generalized console input that parallels the standard C function scanf() or C++ input operators"

:)

Hope this clarifies your question.
Cheers!
Thanks, that cleared it up and the code works fine. Thanks again
thx for the points :)