1

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)

4
  • 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) Commented Nov 10, 2012 at 20:44
  • The exception shows that bash doesnt interpret [1..100] as a sequence but passes it as only value in the list, try for i in $(seq 1 10);. Commented Nov 10, 2012 at 20:46
  • I removed the Java tag because there is no Java in this problem. Commented Nov 10, 2012 at 20:47
  • 2
    Not related to your problem, but you need to look up how to use the modulo operator. Commented Nov 10, 2012 at 20:48

2 Answers 2

4

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

so my algorithm is O(n)...what is modulo?
"In computing, the modulo operation finds the remainder of division of one number by another." - en.wikipedia.org/wiki/Modulo_operation
4

You have to use curly braces, not array brackets:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.