1

Code:

public class Args {
    public static void main(String[] args) {
        if(args.length != 3) {
            System.out.println("Wrong number of arguments");
            return;
        }
    
        int num1 = Integer.parseInt(args[0]);   // 1st argument from args
        int num2 = Integer.parseInt(args[2]);   // 3rd argument from args
    
        String msg = args[0] + args[1] + args[2] + "=";
    
        if(args[1].equals("+"))
            msg += (num1 + num2);
        else if(args[1].equals("-"))
            msg += (num1 - num2);
        else if(args[1].equals("x"))
            msg += (num1 * num2);
        else if(args[1].equals("/"))
            msg += (num1 / num2);
        else
            msg = "Incorrect operator";
    
        System.out.println(msg);
    }
}

Output on command line:

C:\Desktop>java Args
Wrong number of arguments

C:\Desktop>java Args 16 + 4
16+4=20

C:\Desktop>java Args 16 - 4
16-4=12

C:\Desktop>java Args 16 x 4
16x4=64

C:\Desktop>java Args 16 / 4
16/4=4

C:\Desktop>java Args 16 # 4
Incorrect operator

So far everything was working fine. However, when I passed the below argument, I assumed that according to my code the output should have been Incorrect operator, instead it returned Wrong number of arguments. Everything after the ^ character is getting ignored. Why is this happening? I know ^ is used for exponents, apart from this does it have a special meaning in Java which causes the below ignoring behavior?

C:\Desktop>java Args 16 ^ 4
Wrong number of arguments
myverdict
  • 622
  • 8
  • 24
  • 1
    Quick solution: `^` has a special meaning in the Windows terminal, so you have to escape it with another `^` like this: `java Args 16 ^^ 4`. – Lii Sep 06 '21 at 21:03
  • @Lii I tried your solution and it works. However, I had a follow up question, in Java, I have always used \ as an escape character (for e.g. \n for newline). Is ^ also used as an escape character? If yes, under what situations can we use the ^ as an escape character? – myverdict Sep 06 '21 at 21:11
  • @Lii+ it isn't a Windows _terminal_ as such but the Windows _command processor_ CMD. Thus Sam: hat is special in commands typed into CMD, or in a batch file run by CMD, but not input read in a terminal by your own program, or a file read by your own program, or your program's (Java) source. Backslash is special in Java _source_ but not (unless specially coded) in data input or output by running Java code. – dave_thompson_085 Sep 06 '21 at 23:37

0 Answers0