how do i write a program echo in java?

i have an assessment where they asked me to write the program ECHO. This is it:

console> java ECHO Hello you !
Hello
you
!
console>

So i wrote that code for ECHO:

class ECHO {
 public static void main(String[] args){
   String str="Hello You!";
   String[] arr=str.split(" ");
   for(int i=0;i<arr.length;i++){
      System.out.println(arr[i]);

      }
    }
  }

But they told me it is false but i don’t know exactly how to fix it. Can you help me please?

But in my console i have an error which is:

C:UsersUtilisateurIdeaProjectsCodingame_Altensrc>java Echo Hello You !
Error: Could not find or load main class Echo
Caused by: java.lang.ClassNotFoundException: Echo

Why the console is not working?

Answer

They probably want you to use the args parameter from the main-method.

public static void main(String[] args){
    for(String s : args){
        System.out.println(s);
    }
}

This will allow potentional users to define what will be echoed into the console. “Hello you !” will be provided by the user. e.g.:

console> java ECHO Hello you !
Hello
you
!

console> java ECHO A B C
A
B
C

Update: What is String? String is an object, but String[] is an array of String objects. This will give you an idea to use

for(String s : args){ ... } instead of the “traditional” for-loop

Leave a Reply

Your email address will not be published. Required fields are marked *