Click here to Skip to main content
15,881,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when I am inserting a array of char type. I have set rray, but when I run the program it takes less values and print them instead of taking the no. of values which I have initialized.
please check this
Java
import java.io.*;
class charr
{
    public static void main (String args[]) throws IOException
    {
     BufferedReader br= new BufferedReader (new InputStreamReader(System.in));   
     
     char a [] = new char [5];
     for ( int i=0; i<5; i++)
     {
      char n = (char)br.read();
      a[i] = n;
      
        }
    for ( int i=0; i<5; i++)
     {
      System.out.println ( a[i]);
      
        }
        }
}


What I have tried:

I am new to this so i have tried nothing
Posted
Updated 18-Jan-21 5:11am
v2

1 solution

I just tried your code and it works fine*. Please provide more details as to exactly what you are seeing.

*although it does need to be surrounded by a try/catch sequence to check for IOException.


[edit]
I am still not exactly sure what your problem is, but the following code will allow up to 20 characters to be processed. It will terminate on the end of line.
Java
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));   

char a [] = new char [20];
int count;
try {
    for (count = 0; count < 20; count++) {
        char n = (char)br.read();
        if (n == '\n')  // break if end of line
            break;
        a[count] = n;
    }
    for (int i = 0; i < count; i++) {
        System.out.println ( a[i]);        
    }
}
catch (IOException ee) {
    System.out.println (ee);        
}


[/edit]
 
Share this answer
 
v2
Comments
Bhasker Babu 19-Jan-21 3:52am    
But when I run this it takes less values and print them instead of taking the no. of values I have assigned. This is happening only when I use char if I am using int , double or any other data type then it is running correctly
Richard MacCutchan 19-Jan-21 4:14am    
Sorry, but I cannot get it to fail. You must be running some other code than you have posted here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900