-4

Is this code correct? I have mentioned my doubts in the form of comments in some places:

public class pract1
{
    public static void main (String[] args)
    {
        int i;
        String [] array = new String[20]; // Is this declaration correct?
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Array: ");
        array = br.readLine(); // Is this the correct way to accept input from keyboard?
        i=0;
        while(array[i]!='\0') // Can I use the null pointer concept in Java?
        {
            System.out.println("The "+(i+1)+"character is:" +array[i]+"\n"); //Want to print each and every characters in string along with its position
            i++;
        }   
    }
}
Arun
  • 39
  • 1
  • 3
  • 9
  • 7
    Why don't you try to compile and run your code? – Rustam Apr 22 '14 at 08:30
  • use the javac, the compiler will tell you if there are problems. Only the "null pointer" that you are using could be a problem because in java it is simply `null`. Oh, and accessing array[21] will result in an `ArrayIndexoutOfBoundsException` ;) – Theolodis Apr 22 '14 at 08:30
  • br.readLine() returns a String not an array – lakshman Apr 22 '14 at 08:31
  • It looks ok, but I didn't compile it so try doing it. For sure there will be no harm for your computer when you run that code. That think I am sure. – RMachnik Apr 22 '14 at 08:31
  • I think you are comming from the `c`-Language. You should read about the java basics. You can use a String Object and don't need a `char`-array for this case. – Simulant Apr 22 '14 at 08:32
  • @Rustam: Now I don't have Java compiler in my system. Now I am studying Java using some tutorials. I just tried some online compilers but they are showing some random errors. Thats why I have posted this here. – Arun Apr 22 '14 at 08:53

3 Answers3

0

Java string is an object, not array. If you are more comfortable with array, use split() to get an array of String. You should note that each element in the derived array is String Object with only one letter, not primitive Char.

String[] array = "abc".split("");
for(int i; i< array.length; i++)
{
     System.out.println("The "+(i+1)+"character is:" +array[i]+"\n"); 
}   

You may want to read this Question to get the idea of String Object in Java Difference between "char" and "String" in Java

Community
  • 1
  • 1
GingerJim
  • 3,737
  • 6
  • 26
  • 36
0

Array declaration

String [] array = new String[20]; // Is this declaration correct?

This declaration is correct for an array of 20 slots of type String (all of them initialized to null). But you might not need this right away, or not in this form. You don't need to initialize the variable, especially if you overwrite that initialization by an instruction like: array = ....

Getting Input

array = br.readLine(); // Is this the correct way to accept input from keyboard?

Yes, readLine() is the way to go, but as the doc states, and as you will be told by the compiler, readLine(); does not return an array of Strings but a single String. You should use a String variable instead:

// initialize a String variable 'line' containing the whole line without the '\n' at the end
String line = br.readLine();

UPDATE: You could also use the Scanner class instead, that's usually what we do. Then, use sc.nextLine() for similar results as br.readLine(), as stated there.

Printing the chars

System.out.println("The "+(i+1)+"character is:" +array[i]+"\n");
//Want to print each and every characters in string along with its position

You can access the character at a given position in a String via the method charAt(int). Also, you don't have to deal with complicated C stuff such as looking for the end of the string via '\0'. You should instead use a proper for loop, like this:

String line = br.readLine();
for (int i = 0; i < line.length(); i++) {
    System.out.println("The "+(i+1)+" character is: " + line.charAt(i) +"\n");
}

An alternate solution would be to use the toCharArray() method:

String line = br.readLine();
char[] chars = line.toCharArray();
for (int i = 0; i < chars.length; i++) {
    System.out.println("The "+(i+1)+" character is: " + chars[i] +"\n");
}
Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • Hi Joffrey, is there any error with BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); I just tried to compile in a online compiler. But it shows error in BufferedReader. – Arun Apr 22 '14 at 08:55
  • @Arun You can't just try to code without a compiler. You should download Eclipse IDE, it might help you later anyway. Compile the code, and you'll see there is no error in your statement. Moreover, it works. – Joffrey Apr 22 '14 at 08:59
  • @Arun That being said, we usually use a `Scanner` to get user input. Look at my edit. – Joffrey Apr 22 '14 at 08:59
0

This is how you could also do it:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Pract1
{
    public static void main (String[] args)
    {
        String array = ""; //initialize an empty string that will hold the value from the keyboard
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // initialize the BufferedReader

        // while "stop" is not typed on the console, keep running
        while(!array.equals("stop")) {
            System.out.println("Enter the Array: ");
            try {
                array = br.readLine(); // read from the console
                System.out.println("Array:" + array);
                for(int i=0; i<array.length(); i++) { //loop through the input and show the chars
                    System.out.println("Character "+(i+1)+" is: " +array.charAt(i));
                }

            } catch (Exception e) { // catch any exception and show only the message, not the entire stackTrace
                System.out.println("Error: " +  e.getMessage());
            }
            System.out.println("");
        }

    }
}
Liviu Jianu
  • 110
  • 8