0

Trying to run a program that swaps names. The task is simple: input > Alice Bob Alex, output > Alex Bob Alice P.s. Maybe the problem is stupid, but I just recently started programming, so I don't know what to do

I try to run the code in Eclipse - gives an index error. I start in the console - gives an error of the main name. Tried to pass through the internal debugger in Eclipse - writes that I am using obsolete methods. In the end, nothing is clear./

public class Noob {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.print(args[2]);
        System.out.print(" " + args[1]);
        System.out.println(" " + args[0]);
    }
}
  1. Error message from Eclipse:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 0 at noob/noob.Noob.main(Noob.java:7)

  1. Console (the file name is Noob.java)
    1. First I compiled src file (> javac Noob.java)
    2. Then I ran it (> java Noob)

Error: Could not find or load main class Noob Caused by: java.lang.NoClassDefFoundError: noob/Noob (wrong name: Noob)

khelwood
  • 55,782
  • 14
  • 81
  • 108
n00blo
  • 3
  • 1
  • You're running it wrong. It's expecting you to pass three arguments. You can probably edit some kind of run configuration in Eclipse to specify the arguments. – khelwood Sep 03 '19 at 14:58
  • Eclipse can pass in arguments to the application. Click on "Run\Run Configuration" then under _Arguments_ you can pass in a list of names (whitespace separated). Since you're not doing that, the array _args_ is empty, thus throwing index out of bounds error. – SME_Dev Sep 03 '19 at 14:59

3 Answers3

3

You need to pass three arguments

This is the steps you need to follow, to passing arguments

1-) Click on Run -> Run Configurations

2-) Click on Arguments tab

3-) In Program Arguments section , Enter your arguments.

4-) Click Apply

Ahmet Amasyalı
  • 109
  • 1
  • 6
0

You are not passing correctly the values to your program. If you call the program from command line with java myProgram Alice Bob Alex your code should work.

Moreover, you can pass the values to your code through Eclipse directly inside Run Configuration option.

Wolfetto
  • 1,030
  • 7
  • 16
0

Also, it would be better to not hard code the values. Try this:

for (int i=args.length-1; i>=0; i--) {
    System.out.print(args[i] + ' ');
}
System.out.println("");
Grayson
  • 591
  • 1
  • 4
  • 17