bolonomicz
bolonomicz

Reputation: 61

How do I get an input in java without using strings?

So i am trying to implement a very simple program.

i want to set bobi to a variable but without using strings. I am thinking I can do it using just char.

this is what i have so far

System.out.println("Please Enter a four letter name");
char n =
char a = 
char m = 
char e =
System.out.print("His name is ");
System.out.print(n);
System.out.print(a);
System.out.print(m);
System.out.print(e);

with the program i have it is

your program: Enter four letter name:
user: b
user: o
user: b
user: i

I want to be able to enter in one input so its like this

 program: Enter four letter name:
 user: bobi

or is there a better way to approach

Upvotes: 1

Views: 124

Answers (2)

Radiodef
Radiodef

Reputation: 37845

It's certainly possible to read raw data from System.in:

char[] name = new char[4];
try {
    char c;
    int i = 0;
    while((c = (char)System.in.read()) != '\n') {
        if(i < name.length)
            name[i++] = c;
    }
} catch(IOException ioe) {}

There's a couple of notes:

  • System.in is terminated by a new line character (from user pressing 'enter') unlike other streams which are null or -1 terminated.
  • System.in should be compatible with UTF-8. It's probably the same as the system property file.encoding. I can't find an official source that says so but in any case you can just cast it to a char. This question seems to suggest compatibility would be a problem for other readers as well.

Note that this may not be simpler. Compare with using Scanner:

String line = new Scanner(System.in).nextLine();
if(line.length() > 4)
    line = line.substring(0, 4);

And for both cases, you cannot control what the user enters except after they've entered it. You ask for a 4-character name but they can enter "Joe Brown" and they can enter nothing.

Upvotes: 1

christopher
christopher

Reputation: 27346

The System.in stream is the key here. You need to read each byte coming in and run it through an explicit cast to a char.

char n = (char)System.in.read();
char a = (char)System.in.read();

// And so on.

Reading Material so you understand this

  • Using the System.in functionality in Java. Click here.

  • A lesson in Explicit Casts. Click here.

Upvotes: 3

Related Questions