Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in declaring n number of objects using arrays  RSS feed

 
Hari Kumarkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

TRAIL 1:

If I declare a int variable(i) and initializing at run-time for creating "n" number of array of objects

int i = System.in.read(); // Declaring a variable at run-time
System.out.println("i: "+i);
Xyz o[] = new Xyz[i];
System.out.println("o.length :"+o.length);


If I enter 1 as input then it is going to display 49 number of objects ---- HERE I'M FACING PROBLEM; PERHAPS IT SHOULD DISPLAY 1 NUMBER OF OBJECT

TRAIL 2:

If I initialize a int variable(i) and initializing at run-time for creating "n" number of array of objects


int i = 1; // Initializing a variable
Xyz o[] = new Xyz[i];
System.out.println("o.length :"+o.length);


HERE I'M GETTING 1 NUMBER OF OBJECT.

I request you to provide solution for above problem, anticipating a positive reply.
 
Giovanni Lima
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As JavaDoc describe, the method InputStream.read() Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

So when you do:
int i = System.in.read(); // i = 49

You can use java.util.Scanner to make it work.
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
 
vicky Aggarwal
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

you are getting 49 beacuse System.in.read is reading it's ASCII value.
In ASCII 49 is equals to 1.

Also as you Giovanni Lima described it reads next byte.
so if you try
System.out.println(System.in.read());
System.out.println(System.in.read());
System.out.println(System.in.read());


and than give any value you will get following output.
ASCII value of input
13 // ASCII value of CR
10 // ASCII value of LF



you can try also following solution
BufferedReader _bufReader = new BufferedReader(new InputStreamReader(System.in));
choice = _bufReader.readLine();

 
Campbell Ritchie
Marshal
Posts: 55722
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The moral of the story is: don't use System.in.read().

You can use a BufferedReader as suggested, but since 2004 it has been much easier to use a Scanner to read from the keyboard.
 
Hari Kumarkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thank you to all, problem resolved.

Thanks,
Hari Kumarkar
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!