user1559897
user1559897

Reputation: 1484

What is wrong with my bash script that uses my java code?

I am writing a simple java and bash program, but it is not working. Let me know where is wrong.

Bash:

    for i in [1..100]; do 
         echo $i
         java prob2 $i 
    done

Java:

import java.io.*;

public class prob2
{
    public static void main( String[] args )
    {
            int l = args.length;
            if ( l == 1 )
            {
                    int num = Integer.parseInt(args[0]);
                    while ( num != 0 && num != 1)
                            num = num - 2;
                    if ( num == 0 )
                            System.out.println("Even");
                    else if ( num == 1 )
                            System.out.println("Odd");
            }
    }
}

The error I'm getting is:

Exception in thread "main" java.lang.NumberFormatException: For input string: "[1..100]" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at prob2.main(prob2.java:10)

Upvotes: 1

Views: 432

Answers (2)

P.P
P.P

Reputation: 121397

You have to use curly braces, not array brackets:

 for i in {1..100}; do 
         echo $i
         java prob2 $i 
    done

Upvotes: 4

Reese Moore
Reese Moore

Reputation: 11640

That's not how you would do a bash loop. Try this:

for i in `seq 1 100`; do 
     echo $i
     java prob2 $i 
done

As an aside, a faster algorithm for determining if a number is odd or even is to take it modulo 2:

if (num % 2 == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

Upvotes: 4

Related Questions