• Post Reply Bookmark Topic Watch Topic
  • New Topic

System.in.read() (updated with code & output)  RSS feed

 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q. input in an array by using for loop & System.in.read().

when i m using " System.in.read()" in a for loop for continious input it is skipping for Some iterations.
& result in an array is showing garbage value.

//code:


class Try1 {
public static void main(String args[]) throws java.io.IOException {

int arr[] = new int[10];

for(int i=0;i<10;i++){
System.out.println("enter value");
arr[i] = System.in.read();
}

System.out.println("array values");
for(int i=0;i<10;i++)
System.out.println(arr[i]);
}
}

/*
output:


F:\j5se\cr\Try>javac Try1.java

F:\j5se\cr\Try>java Try1
enter value
1
enter value
enter value
enter value
2
enter value
enter value
enter value
3
enter value
enter value
enter value
4
array values
49
13
10
50
13
10
51
13
10
52

*/

pls help me
regards
Amit
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"pure desire" (Amit),

Welcome to JavaRanch!

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names, with a first and a last name.

You can edit your name here.

Thank you for your prompt attention, and enjoy the ranch!

-Marc
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The read() method in an InputStream (like System.in) "reads the next byte of data from the input stream."

Note that the ACSII value for the character '1' is 49. The value for a carriage return is 13, and the value for a new line is 10.

Do you see what's happening here?
 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot marc.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using an instance of java.util.Scanner (constructed with the InputStream System.in) would give you a lot more control here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!